grid布局简介:
Grid布局是将容器划分成“行”和“列”,产生单元格,然后指定“项目所在”的单元格,可以看作是二维布局。
基本概念:
- 容器(container)——有容器属性
- 项目(items)——有项目属性
- 行(row)
- 列(column)
- 间距(gap) ——单元格之间的距离
- 区域(area)—— 自己划分每个单元格占据的区域
- 内容(content)
容器属性
-
grid-template-columns:设置每一列的宽度,可以是具体值,也可以是百分比
grid-template-rows:设置每一行的宽度,可以是具体值,也可以是百分比Document 123456789
结果如图,此时共有三行三列,每行为150px,每列为100px
repeat():第一个参数是重复的次数,第二个参数是所要重复的值
/* grid-template-columns: 100px 100px 100px;也可写成 grid-template-columns:repeat(3,100px) */
/* grid-template-rows: 150px 150px 150px;也可写成 grid-template-rows:repeat(3,150px) */
auto-fill:有时单元格的大小是固定的,但是容器的大小不确定,这个属性就会自动填充
.container{
/*未定义容器的宽高*/
margin-top: 100px;
border: solid 10px red;
margin: auto;
display: grid;
grid-template-columns: repeat(auto-fill,100px);
}
结果如图,会随着浏览器的大小的改变自动填充
fr:为了方便表示比例关系,网格布局提供了fr关键字(fraction的缩写,意为片段)
.container{
margin-top: 100px;
border: solid 10px red;
height: 600px;
width: 600px;
margin: auto;
display: grid;
/* 宽度平均分成4份 */
grid-template-columns: repeat(4,1fr);
/* 高度平均分成3份 */
grid-template-rows: repeat(3,1fr);
}
结果如图,宽度平均分成4份,高度平均分成3份
minmax():函数产生一个长度范围,表示长度就在这个范围之中,它接受两个参数,分别为最小值和最大值
.container{
margin-top: 100px;
border: solid 10px red;
height: 600px;
width: 600px;
margin: auto;
display: grid;
/*共有3列,第一列150px,第二列400px,第三列宽度最小为20px,最大为90px*/
grid-template-columns: 150px 400px minmax(20px,90px);
}
此时3的宽度为50px,位于20px~90px之间
auto:表示由浏览器自己决定长度
.container{
margin-top: 100px;
border: solid 10px red;
height: 600px;
width: 600px;
margin: auto;
display: grid;
/* 中间的宽度由浏览器自己决定 */
grid-template-columns: 100px auto 100px;
}
结果如图,容器总宽600px,第一列和第三列宽100px,浏览器自动将剩余的400px分配为第二列的宽度。
-
grid-column-gap
grid-row-gap
grid-gap(前两个的缩写)
表示项目相互之间的距离,新版本grid-前缀已经删除。.container{
margin-top: 100px;
border: solid 10px red;
height: 600px;
width: 600px;
margin: auto;
display: grid;
grid-template-columns: repeat(3,150px);
grid-template-rows: repeat(3,150px);
column-gap:20px ;<