以前是 tables,后来是 margins 和 floats,再后来是 flexbox ,现在是网格:CSS 总是以新的、更好的方式来简化网页布局编码这项古老的工作。CSS 网格布局模型(CSS Grid Layout Model)可以沿水平和垂直两条轴线创建和更新布局,同时影响元素的宽度和高度。
网格布局并不依赖于元素在标记中的位置,因此你可以在不改变布局的情况下调整元素在标记中的位置。在网格模型中,网格容器元素被网格线划分为网格列和行(统称为网格轨)。现在,让我们来看看如何创建一个网格示例。
Grid 网格示例
要将元素转化为网格容器,可以使用以下三种显示属性之一:
display: grid; – 将元素转换为块状网格容器
display: inline-grid; – 将元素转换为内联网格容器
display: subgrid; – 如果元素是网格项,它将转换为忽略网格模板和网格间隙属性的子网格
正如表格由多个表格单元格组成一样,网格也由多个网格单元格组成。网格项被分配给一组网格单元,这些网格单元统称为网格区域。
我们将创建一个包含五个部分(网格区域)的网格:顶部、底部、左侧、右侧和中央。HTML 由容器 div 内的五个 div 组成。
在 CSS 中,grid-template-areas 属性定义了具有不同网格区域的网格。在其值中,字符串代表网格行,字符串中的每个有效名称代表一列。要创建空网格单元格,需要在行字符串中使用点(.)字符。
网格区域名称可通过各个网格项的 grid-area 属性引用。
.grid-container {
width: 500px;
height: 500px;
display: grid;
grid-template-areas: "top top top"
"left centre right"
"bottom bottom bottom";
}
.grid-top {
grid-area: top;
}
.grid-bottom {
grid-area: bottom;
}
.grid-left {
grid-area: left;
}
.grid-right {
grid-area: right;
}
.grid-centre{
grid-area: centre;
}
因此,这段代码会创建一个有三行三列的网格。最上面的 top 元素占据第一行三列的区域,最下面的 bottom 元素占据最后一行三列的区域。left, centre 和 right 的每个元素都占用中间一行的一列。
现在,我们需要为这些行和列分配尺寸。grid-template-columns 和 grid-template-rows 属性定义了网格轨道的大小(行或列)。
.grid-container {
width: 500px;
height: 500px;
display: grid;
grid-template-areas: "top top top"
"left centre right"
"bottom bottom bottom";
grid-template-columns: 100px auto 100px;
grid-template-rows: 50px auto 150px;
}
这就是我们的 CSS 网格现在的样子(增加了一些样式):
IMAGE: The Grid
网格元素之间的空隙
您可以使用 column-gap 和 row-gap, 或简写属性 gap 在列和行之间添加空白间隔。
.grid-container {
width: 500px;
height: 500px;
display: grid;
grid-template-areas: "top top top"
"left centre right"
"bottom bottom bottom";
grid-template-columns: 100px auto 100px;
grid-template-rows: 50px auto 150px;
gap: 5px 5px;
}
下图显示, gap 属性确实在网格项之间添加了间隙。
Image: Grid with space between tracks
对齐网格内容和子元素
网格容器(.grid-container)的 justify-content 属性可使网格内容沿内联轴(水平轴)对齐,而 align-content 属性可使网格内容沿块轴(垂直轴)对齐。这两个属性都可以有以下值:start, end, center, space-between, space-around 和 space-evenly。
在适用的情况下,轨道(行或列)的大小会缩小,以适应对齐时的内容。请看下面用不同值对齐的网格内容截图。
justify-content: start;
justify-content: end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
align-content: start;
align-content: end;
align-content: center;
align-content: space-between;
align-content: space-around;
align-content: space-evenly;
justify-content 和 align-content 属性都会在网格中对齐整个内容。
要对齐网格区域内的单个项目,可使用另一对对齐属性:justify-items 和 align-items。这两个属性都可以有以下值:start, end, center, baseline(项目沿区域的基本网格线对齐)和stretch (项目填满整个区域)。
本文文字及图片出自 Introduction to the CSS Grid Layout Module