教程 css tutorial

实战案例

本案例使用 CSS Grid 构建响应式图片画廊,展示多张图片自动排列,支持不同尺寸和间距。

目标

  • 定义显式网格列宽
  • 自动生成隐式网格行
  • 自动放置图片项目
  • 控制间距和响应式效果

实战案例示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh-CN">

<head> <meta charset="UTF-8" /> <title>Grid 实战案例:响应式图片画廊</title> <style> body { margin: 20px; font-family: Arial, sans-serif; background-color: #f9fbe7; }

.gallery {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: 150px;
  gap: 15px;
  padding: 10px;
  border: 2px solid #9ccc65;
  border-radius: 8px;
  background-color: #f0f4c3;
}

.gallery-item {
  background-color: #aed581;
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  color: #33691e;
  font-size: 1.2em;
}

.gallery-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

</style> </head>

<body> <div class="gallery"> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片1&quot; alt="图片1"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片2&quot; alt="图片2"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片3&quot; alt="图片3"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片4&quot; alt="图片4"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片5&quot; alt="图片5"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片6&quot; alt="图片6"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片7&quot; alt="图片7"></div> <div class="gallery-item"><img src="https://via.placeholder.com/300x150?text=图片8&quot; alt="图片8"></div> </div> </body>

</html>