Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Giá trị column của flex-direction trong CSS

Giá trị column của flex-direction xếp các flex items theo cột dọc từ trên xuống dưới. Trục chính (main axis) trở thành trục dọc.

Ví dụ: flex-direction: column

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      flex-direction: column;
      background-color: #e67e22;
      padding: 10px;
      gap: 10px;
    }
    .mycontainer > div {
      background-color: white;
      text-align: center;
      line-height: 40px;
      font-size: 25px;
      width: 100px;
      margin: 5px auto;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h1>Quiz</h1>
  <div class="mycontainer">
    <div>Q1</div>
    <div>Q2</div>
    <div>Q3</div>
    <div>Q4</div>
    <div>Q5</div>
    <div>Q6</div>
  </div>
</body>
</html>

Thay đổi trục khi dùng column

Thuộc tínhrow (mặc định)column
Main AxisNgang (← →)Dọc (↑ ↓)
Cross AxisDọc (↑ ↓)Ngang (← →)
justify-contentCăn ngangCăn dọc
align-itemsCăn dọcCăn ngang
flex-wrapXuống dòngSang cột bên

Ví dụ: Căn giữa dọc với column

.v-center {
  display: flex;
  flex-direction: column;
  height: 100vh;
  justify-content: center; /* Căn giữa DỌC */
  align-items: center;     /* Căn giữa NGANG */
}

column-reverse: Đảo ngược thứ tự

.reverse-column {
  display: flex;
  flex-direction: column-reverse; /* Item cuối lên trên cùng */
}

Responsive: Column mobile, Row desktop

.flex-col-md-row {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
@media (min-width: 768px) {
  .flex-col-md-row {
    flex-direction: row;
    flex-wrap: wrap;
  }
  .flex-col-md-row > * {
    flex: 1 1 300px;
  }
}

Shorthand flex-flow

.container {
  flex-flow: column wrap; /* direction + wrap */
}