Skip to content
WonvyWonvy

CSS Grid 布局实战案例

一句话结论

CSS Grid 是创建复杂布局的强大工具,特别适合二维布局场景。

基础网格布局

简单的三列布局

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

.item {
  padding: 20px;
  background: #f0f0f0;
  border-radius: 8px;
}

响应式网格

css
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}

/* 移动端单列 */
@media (max-width: 768px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
}

复杂布局示例

经典布局:Header、Sidebar、Main、Footer

css
.layout {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
  gap: 16px;
}

.header {
  grid-area: header;
  padding: 16px;
  background: #333;
  color: white;
}

.sidebar {
  grid-area: sidebar;
  padding: 16px;
  background: #f5f5f5;
}

.main {
  grid-area: main;
  padding: 16px;
}

.footer {
  grid-area: footer;
  padding: 16px;
  background: #333;
  color: white;
}

/* 移动端布局 */
@media (max-width: 768px) {
  .layout {
    grid-template-areas:
      "header"
      "main"
      "sidebar"
      "footer";
    grid-template-columns: 1fr;
  }
}

卡片网格布局

css
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  padding: 24px;
}

.card {
  display: flex;
  flex-direction: column;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 12px;
}

.card-content {
  flex: 1;
  color: #666;
  line-height: 1.6;
}

.card-footer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

对齐和间距

css
.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  
  /* 对齐方式 */
  align-items: start;      /* 垂直对齐 */
  justify-items: center;   /* 水平对齐 */
  
  /* 内容对齐 */
  align-content: center;   /* 整个网格垂直对齐 */
  justify-content: space-between; /* 整个网格水平对齐 */
}

可复用的要点

  • 使用 repeat()minmax() 创建响应式网格
  • 使用 grid-template-areas 定义布局结构
  • 合理使用 gap 控制间距
  • 结合媒体查询实现响应式
  • 使用 auto-fillauto-fit 自动适应容器

参考链接