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

Giá trị center của align-content trong CSS Flexbox

Giá trị center của align-content đặt các flex lines (các hàng sau wrap) ở giữa container dọc trục cross-axis.

Điều kiện

  • display: flex + flex-wrap: wrap
  • Container có chiều cao (height/min-height) > tổng chiều cao các dòng

Ví dụ: align-content: center

<!DOCTYPE html>
<html>
<head>
  <style>
    .mycontainer {
      display: flex;
      height: 200px;
      background-color: #e74c3c;
      align-content: center;
      flex-wrap: wrap;
      padding: 10px;
      gap: 10px;
    }
    .mycontainer > div {
      background-color: #f1c40f;
      text-align: center;
      line-height: 60px;
      font-size: 30px;
      width: 100px;
      margin: 5px;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h1>Queue</h1>
  <div class="mycontainer">
    <div>Q1</div>
    <div>Q2</div>
    <div>Q3</div>
    <div>Q4</div>
    <div>Q5</div>
    <div>Q6</div>
    <div>Q7</div>
    <div>Q8</div>
  </div>
</body>
</html>

So sánh align-content values

Container: 200px | 3 lines × 60px = 180px | Gap: 20px | Remaining: 20px

flex-start:     | Line1 | Line2 | Line3 | 20px空白 |
center:         | 10px | Line1 | Line2 | Line3 | 10px |
flex-end:       | 20px空白 | Line1 | Line2 | Line3 |
space-between:  | Line1 | 10px | Line2 | 10px | Line3 |
space-around:   | 5px | Line1 | 10px | Line2 | 10px | Line3 | 5px |
stretch:        | Line1(66px) | Line2(66px) | Line3(66px) | (chia đều 20px)

Ứng dụng: Modal/Dialog căn giữa hoàn hảo

.modal-overlay {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.5);
}
.modal {
  width: 90%;
  max-width: 500px;
  background: white;
  border-radius: 8px;
  padding: 2rem;
}

Lưu ý

  • Chỉ hoạt động khi có nhiều dòng (flex-wrap tạo ra)
  • Single line: dùng align-items: center
  • Trong Grid Layout, align-content cũng hoạt động tương tự