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

Căn chỉnh Left-Right containers với CSS Flex


Dùng flexbox để đẩy 2 container ra 2 bên trái/phải: justify-content: space-between.

Ví dụ 1: Ngang hàng (Row)

<!DOCTYPE html>
<html>
<head>
  <style>
    #container {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      margin: 2%;
      padding: 5%;
      background: url("bg.jpg") center/cover;
      color: white;
      min-height: 200px;
      align-items: center;
    }
    .box {
      padding: 20px 40px;
      border: 2px solid red;
      border-radius: 8px;
      background: rgba(0,0,0,0.3);
    }
  </style>
</head>
<body>
  <div id="container">
    <div class="box">Left</div>
    <div class="box">Right</div>
  </div>
</body>
</html>

Ví dụ 2: Dọc cột (Column wrap)

<style>
  #container2 {
    display: flex;
    flex-flow: column wrap;
    height: 300px;
    padding: 2%;
    background: url("bg2.jpg") center/cover;
  }
  img {
    margin: 10px;
    width: 60px;
    border-radius: 50%;
  }
</style>
<div id="container2">
  <img src="avatar.jpg"><img src="avatar.jpg"><img src="avatar.jpg">
  <img src="avatar.jpg"><img src="avatar.jpg"><img src="avatar.jpg">
</div>

Kết quả

  • Ví dụ 1: 2 box "Left" và "Right" ở 2 đầu container, căn giữa dọc
  • Ví dụ 2: 6 avatar xếp thành 2 cột dọc (column wrap), xuống hàng khi hết chỗ

Mẹo

  • margin-left: auto trên item thứ 2 = đẩy sang phải (tương tự space-between)
  • Kết hợp align-items: center/flex-start/flex-end cho cross-axis