
CSS的grid布局
grid
display:grid 或 display:inline-grid 来创建一个网格容器
1 2 3 4 5 6 7 8 9
| <div class="wrapper"> <div class="one item">One</div> <div class="two item">Two</div> <div class="three item">Three</div> <div class="four item">Four</div> <div class="five item">Five</div> <div class="six item">Six</div> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| .wrapper { margin: 60px; display: grid; grid-template-columns: repeat(3, 200px); grid-gap: 20px; grid-template-rows: 100px 200px; } .one { background: #19CAAD; } .two { background: #8CC7B5; } .three { background: #D1BA74; } .four { background: #BEE7E9; } .five { background: #E6CEAC; } .six { background: #ECAD9E; } .item { text-align: center; font-size: 200%; color: #fff; }
|
auto-fill
auto-fill 关键字:表示自动填充,让一行(或者一列)中尽可能的容纳更多的单元格。grid-template-columns: repeat(auto-fill, 200px) 表示列宽是 200 px,但列的数量是不固定的,只要浏览器能够容纳得下,就可以放置元素
1 2 3 4 5 6 7
| .wrapper-2 { display: grid; grid-template-columns: repeat(auto-fill, 200px); grid-gap: 5px; grid-auto-rows: 50px; }
|
fr
fr 关键字:Grid 布局还引入了一个另外的长度单位来帮助我们创建灵活的网格轨道。fr 单位代表网格容器中可用空间的一等份。grid-template-columns: 200px 1fr 2fr 表示第一个列宽设置为 200px,后面剩余的宽度分为两部分,宽度分别为剩余宽度的 1/3 和 2/3。
1 2 3 4 5 6 7
| .wrapper-3 { display: grid; grid-template-columns: 200px 1fr 2fr; grid-gap: 5px; grid-auto-rows: 50px; }
|
minmax
minmax() 函数:我们有时候想给网格元素一个最小和最大的尺寸,minmax() 函数产生一个长度范围,表示长度就在这个范围之中都可以应用到网格项目中。它接受两个参数,分别为最小值和最大值。grid-template-columns: 1fr 1fr minmax(300px, 2fr) 的意思是,第三个列宽最少也是要 300px,但是最大不能大于第一第二列宽的两倍。
1 2 3 4 5 6 7
| .wrapper-4 { display: grid; grid-template-columns: 1fr 1fr minmax(300px, 2fr); grid-gap: 5px; grid-auto-rows: 50px; }
|
auto
auto 关键字:由浏览器决定长度。通过 auto 关键字,我们可以轻易实现三列或者两列布局。grid-template-columns: 100px auto 100px 表示第一第三列为 100px,中间由浏览器决定长度。类似flex: 1;
1 2 3 4 5 6 7
| .wrapper-5 { display: grid; grid-template-columns: 100px auto 100px; grid-gap: 5px; grid-auto-rows: 50px; }
|
gap
grid-row-gap 属性、grid-column-gap 属性分别设置行间距和列间距。 grid-gap 属性是两者的简写形式。
grid-row-gap: 10px 表示行间距是 10px,grid-column-gap: 20px 表示列间距是 20px。grid-gap: 10px 20px 实现的效果是一样的