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

Xây dựng Grid View Responsive với CSS

Grid View responsive chia layout thành các cột tỷ lệ phần trăm, sử dụng float (cách cũ) hoặc Flexbox/Grid (cách hiện đại).

Ví dụ cũ: Float-based Grid

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    * { box-sizing: border-box; }
    .header {
      border: 1px solid #333;
      padding: 10px;
      text-align: center;
    }
    .leftmenu {
      width: 30%;
      float: left;
      padding: 10px;
      border: 1px solid #333;
    }
    .content {
      width: 70%;
      float: left;
      padding: 10px;
      border: 2px dotted #333;
    }
    @media (max-width: 768px) {
      .leftmenu, .content { width: 100%; float: none; }
    }
  </style>
</head>
<body>
  <div class="header"><h1>Header</h1></div>
  <div class="leftmenu">
    <ul><li>Menu 1</li><li>Menu 2</li><li>Menu 3</li></ul>
  </div>
  <div class="content">
    <h1>Demo</h1>
    <p>Nội dung chính...</p>
  </div>
</body>
</html>

Cách hiện đại: CSS Grid (Khuyên dùng)

.grid-layout {
  display: grid;
  grid-template-columns: 1fr 3fr; /* Sidebar 25%, Content 75% */
  gap: 1.5rem;
  padding: 1rem;
}
@media (max-width: 768px) {
  .grid-layout {
    grid-template-columns: 1fr; /* 1 cột trên mobile */
  }
}

Cách hiện đại: Flexbox

.flex-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  padding: 1rem;
}
.sidebar { flex: 0 0 30%; min-width: 250px; }
.content { flex: 1 1 70%; min-width: 300px; }

Responsive Grid System (12 cột)

.row { display: flex; flex-wrap: wrap; margin: 0 -12px; }
.col { padding: 0 12px; box-sizing: border-box; }
.col-1 { flex: 0 0 8.33%; max-width: 8.33%; }
.col-2 { flex: 0 0 16.66%; max-width: 16.66%; }
.col-3 { flex: 0 0 25%; max-width: 25%; }
.col-4 { flex: 0 0 33.33%; max-width: 33.33%; }
.col-6 { flex: 0 0 50%; max-width: 50%; }
.col-12 { flex: 0 0 100%; max-width: 100%; }

@media (max-width: 768px) {
  .col-sm-12 { flex: 0 0 100%; max-width: 100%; }
}

CSS Grid: Auto-fit / Auto-fill (Magic)

.auto-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
}
/* Tự động: 1 cột mobile, 2 cột tablet, 3-4 cột desktop */

So sánh phương pháp

Phương phápƯu điểmNhược điểm
FloatHỗ trợ IE cũCần clearfix, phức tạp, limited
Flexbox1D layout, dễ căn chỉnh, gap supportKhó kiểm soát 2D chính xác
CSS Grid2D layout mạnh mẽ, auto-fit/fill, linesHọc phức tạp hơn