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

Tạo cột cùng chiều cao (Equal Height Columns) với CSS

Để các cột có chiều cao bằng nhau bất kể nội dung, có thể dùng display: table / table-cell (cách cũ) hoặc Flexbox/Grid (cách hiện đại).

Cách 1: Table-cell (ví dụ gốc)

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
  body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
  .container { display: table; width: 100%; }
  .column { display: table-cell; padding: 16px; background-color: greenyellow; }
  .column:nth-of-type(2n-1) { color: red; background-color: yellow; }
</style>
</head>
<body>
<h1>Equal Height Columns Example</h1>
<div class="container">
  <div class="column"><h2>Column 1</h2><h2>Column 1</h2><h2>Column 1</h2></div>
  <div class="column"><h2>Column 2</h2><h2>Column 2</h2><h2>Column 2</h2></div>
  <div class="column"><h2>Column 3</h2><h2>Column 3</h2><h2>Column 3</h2></div>
</div>
</body>
</html>

Cách 2: Flexbox (Khuyến nghị hiện đại)

.container { display: flex; }
.column { flex: 1; padding: 16px; }
/* Các cột tự động cùng chiều cao nhờ align-items: stretch (mặc định) */

Cách 3: CSS Grid

.container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }

So sánh

  • Table-cell: Hỗ trợ IE8+, nhưng cứng nhắc, khó responsive
  • Flexbox: Linh hoạt, responsive dễ dàng, hỗ trợ tốt
  • Grid: Mạnh nhất cho layout 2D, kiểm soát gap, alignment tốt nhất

Với dự án mới, hãy ưu tiên Flexbox (1D) hoặc Grid (2D).