如何用CSS Grid实现特定行三列的混合网格布局?
用CSS Grid实现动态列数的多行布局
当然可以实现,你之前遇到的问题是因为CSS Grid的列轨道是全局统一的,不能在grid-template-areas的不同行里定义不同数量的列(比如一行2列、一行3列),这会导致网格轨道计算混乱。
要实现你想要的布局,我们可以先定义足够多的等宽列轨道(比如取2和3的最小公倍数6列),然后通过grid-column属性控制每个元素跨多少列,以此模拟不同行的列数:
实现代码
CSS
section { display: grid; /* 定义6个等宽列轨道,适配2列/3列的布局需求 */ grid-template-columns: repeat(6, 1fr); gap: 4px; /* 可选,添加元素间距提升可读性 */ } div { height: 20px; } /* 第一行:2个等宽元素,各跨3列 */ div:nth-of-type(1) { background: red; grid-column: 1 / span 3; } div:nth-of-type(2) { background: green; grid-column: 4 / span 3; } /* 第二行:1个整行元素,跨全部6列 */ div:nth-of-type(3) { background: yellow; grid-column: 1 / -1; } /* 第三行:3个等宽元素,各跨2列 */ div:nth-of-type(4) { background: pink; grid-column: 1 / span 2; } div:nth-of-type(5) { background: aqua; grid-column: 3 / span 2; } div:nth-of-type(6) { background: black; grid-column: 5 / span 2; } /* 第四行:1个整行元素,跨全部6列 */ div:nth-of-type(7) { background: gray; grid-column: 1 / -1; }
HTML
<section> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </section>
原理说明
- 先通过
grid-template-columns: repeat(6, 1fr)创建6个等宽列,这样既能拆分出2个各占3列的等宽元素(对应2列布局),也能拆分出3个各占2列的等宽元素(对应3列布局)。 - 使用
grid-column: span N控制元素跨越的列数,1 / -1是快捷写法,表示从第一列跨到最后一列(占满整行)。 - 这种方式避开了
grid-template-areas的列数限制,更灵活地实现不同行的列数变化。
内容的提问来源于stack exchange,提问作者Jon Sud
相关产品推荐
相关产品推荐

