老规矩,直接上代码。
1.css里的Grid布局【网格布局】:
html代码:
<div class="cotn">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
css代码:
.cotn{
display: grid;
grid-templated-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;
}
2.基础响应单位:fraction【简写:fr】
.cotn{
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 50px 50px;
}
如果将grid-template-columns的值更改为1fr 2fr 3fr,第二列的宽度将会是其他两列的两倍。总宽度是4个fraction单位,第二列占据两个fraction,其它的各占一个。
3.高级响应:
repeat()函数:一个强大指定列和行的方法。
.cotn{
display: grid;
grid-grap: 5px;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(2, 50px);
}
repeat(3, 100px)等于100px 100px 100px。第一个参数指定行与列的数量,第二个参数指定它们的宽度。
4.auto-fit:跳过固定数量的列,换成自适应数量。
.cotn{
display: grid;
grid-grap: 5px;
grid-template-columns: repeat(auto-fit, 100px);
grid-template-rows: repeat(2 100px;)
}
栅格将会根据容器的宽度调整数量,网格通常左右侧会有留白情况。
5.minmax()函数:
.cotn{
display: grid;
grid-grap: 5px;
grid-template-columns: repeat(auto-fit, minmax(100px , 1fr));
grid-template-rows: repeat(2 100px;)
}
minmax()函数会将可用的空间均匀的分给每列,这些列变成了fraction单位,而不是100px。
6.添加图片:
<div><img src = "img/fp.png" /></div>
.cotn > div > img{
width: 100%;
height: 100%;
object-fit: cover;
}
结束语:
浏览器支持的情况,全球77%的网站支持CSS Grid,而且比例还在逐步上升。