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

Tạo bố cục lưới 2 cột (2-column layout grid) với CSS


Bố cục 2 cột thường dùng cho sidebar + content, hoặc split screen.

Cách 1: Float

.left, .right { float: left; width: 50%; box-sizing: border-box; }
.container::after { clear: both; }

Cách 2: Flexbox (khuyên dùng)

.container { display: flex; gap: 20px; }
.left, .right { flex: 1; min-width: 0; }
@media (max-width: 768px) { .container { flex-direction: column; } }

Cách 3: CSS Grid

.container { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
@media (max-width: 768px) { .container { grid-template-columns: 1fr; } }

Cách 4: Split screen fixed (position:fixed)

.left, .right {
  position: fixed;
  top: 0; bottom: 0;
  width: 50%;
  overflow-y: auto;
}
.left { left: 0; background: #24005f; }
.right { right: 0; background: #38012c; }

Ví dụ Flexbox hoàn chỉnh

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body { font-family: Arial; margin: 0; min-height: 100vh; }
    .container { display: flex; min-height: 100vh; }
    .left, .right { 
      flex: 1; 
      padding: 40px; 
      box-sizing: border-box;
      color: white;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .left { background: rgb(36, 0, 95); }
    .right { background: rgb(56, 1, 44); }
  </style>
</head>
<body>
  <div class="container">
    <div class="left"><h1>Bên Trái</h1></div>
    <div class="right"><h1>Bên Phải</h1></div>
  </div>
</body>
</html>

Kết quả

Hai cột bằng nhau, căn giữa nội dung, full height viewport, responsive stack dọc trên mobile.