You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS Grid实现指定页面布局?(附给定HTML/CSS代码)

基于CSS Grid实现专辑页面布局解决方案

核心布局思路

  • 将最外层的article设为主网格容器,所有直接子元素(.album_data、.cover、.song_list、.anecdotes)都在这个网格内定位,这是解决布局混乱的关键。
  • .album_data(文本区块)与.cover(黄色封面区块)属于同一主网格的不同单元格,.song_list(橙色歌单区块)跨主网格所有列,无需单独设置独立网格。

完整CSS实现代码

/* 全局默认样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 主网格容器:控制整体布局 */
article.best {
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 20px;
  border: 3px solid rgba(227, 227, 227, 0.4);
  padding: 20px;
  display: grid;
  /* 左侧宽列 + 右侧封面列 */
  grid-template-columns: 3fr 1fr;
  /* 标题行 + 内容行 + 歌单行 + 轶事行 */
  grid-template-rows: auto 1fr auto auto;
  gap: 20px; /* 网格间距,避免元素拥挤 */
}

/* 专辑信息区块:左侧列,跨前两行 */
.album_data {
  grid-column: 1 / 2;
  grid-row: 1 / 3;
  /* 内部垂直排版用flex更简洁 */
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 封面区块:右上角单元格 */
.cover {
  grid-column: 2 / 3;
  grid-row: 1 / 2;
  position: relative;
  width: 100%;
  aspect-ratio: 1/1; /* 保持正方形比例 */
}
.cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
/* 实现hover切换图片效果 */
.cover:hover .show_not_hover {
  opacity: 0;
}
.cover .show_not_hover {
  transition: opacity 0.3s ease;
}

/* 歌单区块:跨所有列,底部橙色区域 */
.song_list {
  grid-column: 1 / -1; /* 自动跨所有列 */
  grid-row: 3 / 4;
  background-color: #ff9933; /* 匹配目标布局的橙色背景 */
  padding: 20px;
  border-radius: 10px;
  /* 内部两列布局 */
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

/* 轶事列表:跨所有列,最底部区域 */
.anecdotes {
  grid-column: 1 / -1;
  grid-row: 4 / 5;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  list-style: none;
}
.anecdotes li {
  padding: 10px;
  background-color: rgba(255,255,255,0.1);
  border-radius: 8px;
  color: #fff;
}
/* 处理特殊布局类 */
.anecdotes .two_wide {
  grid-column: span 2; /* 跨两列 */
}
.anecdotes .empty {
  visibility: hidden; /* 空元素隐藏不占位 */
}

/* 文本样式优化 */
.h1-spring {
  font-family: Piximisa;
  font-weight: bold;
  font-size: 5vw;
  color: rgba(217, 217, 217, 0.7);
  margin: 0;
}
.h2-spring {
  font-family: Louis;
  font-size: 2.4vw;
  color: rgb(246, 246, 246);
  margin: 0 0 20px 0;
}
.musicians, .album_description {
  color: #fff;
  line-height: 1.5;
}
.musicians ul, .song_list ul {
  list-style: disc inside;
  margin-top: 10px;
  color: #fff;
}
.song_list h2 {
  color: #fff;
  margin-bottom: 10px;
}

关键细节说明

  1. 主网格统一控制:所有区块都在article网格内定位,避免了之前子网格独立导致的布局错位问题。
  2. 区块精准定位:
    • .album_data占据左侧核心区域,内部用flex垂直排列文本内容,适配不同长度的文本。
    • .cover通过aspect-ratio固定正方形,hover切换效果用透明度过渡实现,流畅自然。
    • .song_list跨整行宽度,内部再分两列放置两个歌单,完全匹配目标布局的橙色区块样式。
  3. 轶事列表适配:用三列网格布局,通过span类控制指定元素跨列,空元素隐藏不影响整体布局。

内容的提问来源于stack exchange,提问作者Thea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:25:18