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

Căn chỉnh cột DIV Left-Center-Right với CSS Flex justify-content


Dùng justify-content trên flex container để phân bố items theo trục chính.

Các giá trị chính

Giá trịMô tả
flex-startDồn về đầu (mặc định)
flex-endDồn về cuối
centerCăn giữa
space-betweenItem đầu/cuối chạm mép, khoảng cách đều giữa các item
space-aroundKhoảng cách đều quanh mỗi item (nửa ở 2 đầu)
space-evenlyKhoảng cách hoàn toàn đều giữa tất cả item và mép

Ví dụ 1: 3 cột Left-Center-Right

<!DOCTYPE html>
<html>
<head>
  <style>
    #root {
      margin: 5%;
      display: flex;
      justify-content: space-between;  /* Left - Center - Right */
      gap: 20px;
    }
    .element {
      flex: 1;
      padding: 40px;
      border-radius: 15px;
      text-align: center;
      font-size: 2rem;
      font-weight: bold;
      color: white;
    }
    #one { background: #b798e1; }
    #two { background: #236fa0; }
    #three { background: #43946a; }
  </style>
</head>
<body>
  <div id="root">
    <div class="element" id="one">Left</div>
    <div class="element" id="two">Center</div>
    <div class="element" id="three">Right</div>
  </div>
</body>
</html>

Ví dụ 2: 6 items space-evenly

<style>
  #root2 {
    display: flex;
    justify-content: space-evenly;
    padding: 20px;
    background: #f0f0f0;
    border-radius: 12px;
  }
  #root2 > div {
    padding: 20px 40px;
    border-radius: 15px;
    font-weight: bold;
    font-size: 1.5rem;
  }
  #root2 > div:nth-child(odd) { background: lightblue; }
  #root2 > div:nth-child(even) { background: orange; }
</style>
<div id="root2">
  <div>1</div><div>2</div><div>3</div>
  <div>4</div><div>5</div><div>6</div>
</div>

Kết quả

  • Ví dụ 1: 3 cột cách đều 2 đầu, không gian giữa bằng nhau
  • Ví dụ 2: 6 ô xen kẽ màu, khoảng cách đều hoàn toàn