初学 grid 布局的时候就觉得很神奇,CSS 竟然有属性可以做二维布局,再往后学就进入深水区了,发现 grid 布局的属性有 display,grid-template-columns,grid-template-rows,grid-gap,grid-template-areas,grid-auto-flow,place-items,place-content,grid-auto-columns,grid-auto-rows 属性,而且有的属性包含多个关键字,如 grid-template-columns 属性有 repeat(),auto-fill,fr,minmax,auto 等关键字。学习成本陡然增加。学到一半果然先放弃了,还是回到要解决的问题本身。
下图就是要实现的效果。宽度方面,9个方块里面前6个方块的宽度都是占4份,后三个方块的宽度都是占3份。高度方面,9个方块里面有7个方块的高度都是占1份,2个方块的高度占2份。
翻了翻资料,发现前面6个规整的方块还是较容易实现的,只要控制第二块和第三块高度不一样就行了,可是后面三块的宽度不一致了,这个怎么实现呢?找了下中文社区的例子,没看到符合要求的。只能去 google 搜,直到找到下面这个例子才豁然开朗,原来可以将模块拆分成这么多,这里面包含了3等份和4等份的情况,这拆分的模块数不就是求最大公倍数。看完就跟着写起来了。
代码实现后还是挺精简的,只用到了6个属性。其中 display 属性指定网格布局,grid-template-rows 属性指定行高,grid-template-columns 属性指定列宽,gap 属性指定行与行、列与列的间距,grid-column 指定左右边框的网格线,grid-row 指定上下边框的网格线。
另外,这里还使用了2个关键字,span 表示跨域的网格线,repeat 相当于一个函数,可以简化重复的值
<div id="wrapper">
<div class="item1" style="background-color: red">1</div>
<div class="item2" style="background-color: blue">2</div>
<div class="item3" style="background-color: yellow">3</div>
<div class="item4" style="background-color: green">4</div>
<div class="item5" style="background-color: black">5</div>
<div class="item6" style="background-color: hotpink">6</div>
<div class="item7" style="background-color: forestgreen">7</div>
<div class="item8" style="background-color: firebrick">8</div>
<div class="item9" style="background-color: rebeccapurple">9</div>
</div>
#wrapper {
width: 100%;
display: grid;
grid-template-rows: repeat(3, 50px);
grid-template-columns: repeat(12, 25px);
gap: 20px;
}
.item1,
.item2,
.item3,
.item4,
.item5,
.item6 {
grid-column: span 3;
}
.item7,
.item8,
.item9 {
grid-column: span 4;
}
.item2,
.item3 {
grid-row: span 2;
}
小结
学以致用才能加深对概念的理解,学习 grid 布局可以先记住主要用法,再多写几个例子,特别是要写奇怪又有代表性的例子。上面的例子就是很好的体现,网格不规整的时候就要想办法拆分网格,这样才能写出更灵活的布局。
参考链接:
- ruanyifeng.com/blog/2019/0…
- www.quackit.com/css/grid/tu…