共计 1406 个字符,预计需要花费 4 分钟才能阅读完成。
简介
Flex 布局是轴线布局,能够说是 一维布局 。Grid 布局则是将容器划分成 ” 行 ” 和 ” 列 ”,产生单元格,而后指定每一页单元格,能够看作是 二维布局。Flex 布局和 Grid 布局不抵触,它们的应用场景是不一样的。
概念
容器和我的项目
采纳网格布局的区域,称为 ” 容器 ”(container)。容器外部采纳网格定位的子元素,称为 ” 我的项目 ”(item)。例如:
<div class="container">
<div class="item"><span>1</span></div>
<div class="item"><span>2</span></div>
<div class="item"><span>3</span></div>
</div>
上述代码中,container
就是容器,item
就是我的项目,而 span
不属于我的项目 (除非span
也设为 grid
,那么span
就是 item
的我的项目)。
行和列
容器外面的程度区域称为 行(row)
,。垂直区域称为 列(column)
。
单元格
行与列相交的区域为 cell
单元格
网格线
划分网格的线,称为 ” 网格线 ”(grid line)。程度网格线划分出行,垂直网格线划分出列。
失常状况下,n
行有 n + 1
根程度网格线,m
列有 m + 1
根垂直网格线,比方三行就有四根程度网格线。
如果用 Chrome 浏览器关上调试面板,在构造里能够看到一个 grid
的标记,点击会显示网格线,并标有相应的 序号,如下图所示:
容器属性
display 属性
gird
为块级元素,inline-grid
为行内元素。
grid-template-columns 和 grid-template-rows
grid-template-columns
属性定义每一列的 列宽 grid-template-rows
属性定义每一行的 行高 。
如图所示:
.container{
grid-template-columns: 100px 50px 100px;
grid-template-rows: 50px 100px 50px;
}
除了应用相对单位,也能够应用百分比。
.container{
grid-template-columns: 20% 30% 50%;
grid-template-rows: 20% 30% 50%;
}
repeat()repeat()
承受两个参数,第一个参数是反复的次数,第二个参数是所要反复的值。例如:
.container {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
}
也能够反复一组数值:
grid-template-columns: repeat(2, 30px 50px 80px);
auto-fill
有的时候,单元格的大小是固定的,然而容器的大小不确定。如果心愿每一行(或每一列)包容尽可能多的单元格,这时能够应用 auto-fill
关键字示意主动填充。
如果是列填充值大于容器宽度,则换行显示。
如果是行填充的值大于容器高度,则残余的内容将会超出容器。
.container {
margin: 20px;
width: 600px;
height: 300px;
display: grid;
grid-template-columns: repeat(auto-fill, 250px);
grid-template-rows: repeat(auto-fill, 100px);
}