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

如何使用grid-template-areas实现DOM顺序不变的全高侧边栏3×3 CSS网格布局

完整实现代码

CSS

html, body {
  margin: 0;
  height: 100%;
}
* {
  box-sizing: border-box;
}
.parent {
  display: grid;
  height: 100vh;
  /* 定义3列:侧边栏宽240px,剩余两列均分宽度,可按需调整数值 */
  grid-template-columns: 240px 1fr 1fr;
  /* 定义3行:三等分高度,可按需调整数值 */
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas: 
    "one three three"
    "one three three"
    "one two two";
}
.one {
  grid-area: one;
  border: 1px solid #000;
}
.three {
  grid-area: three;
  border: 1px solid #000;
}
.two {
  grid-area: two;
  border: 1px solid #000;
}

HTML

<div class="parent">
    <div class="one">one</div>
    <div class="three">three</div>
    <div class="two">two</div>
</div>

核心修改说明

  • 修正了grid-template-areas的语法错误:每行定义的区域数量必须和网格列数一致,所有区域定义字符串不需要额外加分号分隔
  • 给根节点和.parent容器设置了100%视口高度,保证侧边栏可以占满全屏
  • 显式定义了grid-template-columns和grid-template-rows的尺寸规则,匹配3×3网格结构
  • 区域分配上让one占满第一列全部3行实现全屏高侧边栏,完全不需要修改原有DOM节点顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:06:04