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

CSS3 Flexible Box Layouts (Flexbox) - Tổng quan


Flexbox (Flexible Box Layout) là chế độ layout CSS3 mạnh mẽ cho layout 1 chiều (hàng hoặc cột).

Thuộc tính Container

Thuộc tínhMô tả
flex-directionrow | row-reverse | column | column-reverse
flex-wrapnowrap | wrap | wrap-reverse
flex-flowShorthand: direction + wrap
justify-contentCăn chỉnh trục chính: center, space-between, space-around, space-evenly...
align-itemsCăn chỉnh trục chéo: stretch, center, flex-start, flex-end, baseline
align-contentCăn chỉnh nhiều dòng (khi wrap)

Thuộc tính Item

Thuộc tínhMô tả
flex-growKhả năng mở rộng (mặc định 0)
flex-shrinkKhả năng thu nhỏ (mặc định 1)
flex-basisKích thước ban đầu trước phân bổ
flexShorthand: grow shrink basis
align-selfGhi đè align-items cho item riêng
orderThứ tự hiển thị (mặc định 0)

Ví dụ

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .container {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-evenly;
      background-color: lightblue;
      padding: 20px;
      gap: 20px;
    }
    .box {
      width: 200px;
      padding: 20px;
      margin: 10px;
      font-size: 30px;
      color: white;
      text-align: center;
      border-radius: 8px;
    }
    .box1 { background: rgb(71, 30, 255); align-self: flex-start; }
    .box2 { background: rgb(14, 126, 79); }
    .box3 { background: rgb(168, 60, 10); }
    .box4 { background: rgb(26, 10, 168); }
  </style>
</head>
<body>
  <h1>Flex Layout Example</h1>
  <div class="container">
    <div class="box box1">1</div>
    <div class="box box1">2</div>
    <div class="box box1">3</div>
    <div class="box box2">1</div>
    <div class="box box2">2</div>
    <div class="box box2">3</div>
    <div class="box box3">1</div>
    <div class="box box3">2</div>
    <div class="box box3">3</div>
    <div class="box box4">1</div>
    <div class="box box4">2</div>
    <div class="box box4">3</div>
  </div>
</body>
</html>

Kết quả

Container flex wrap, các box màu khác nhau phân bố đều (space-evenly), xuống dòng tự động khi thiếu chỗ.