grid栅格布局
郭旭升 Lv6

what

CSS Grid 布局是一种二维布局模型,允许同时在行和列方向上对元素进行布局。与传统的基于盒模型的布局模型不同,CSS Grid 布局可以更精确地控制布局中的行、列、单元格等元素,并且可以自适应不同大小的屏幕。

相比于传统的布局方式,CSS Grid 布局提供了更加强大的布局能力和更简单的代码实现,这使得它成为了开发响应式布局的重要工具之一。
a grid container and using the grid-template-rows, grid-template-columns, grid-row, and grid-column properties, you can create flexible and responsive layouts that work well on a variety of devices.

使用

在 HTML 页面中,可以通过以下方式定义 Grid 布局:

1
2
3
4
5
.container {
display: grid;
grid-template-columns: 50px 50px 50px;
grid-template-rows: 100px 100px;
}

在这个例子中,通过 display: grid 属性定义一个 Grid 布局容器,通过 grid-template-columns 和 grid-template-rows 属性分别设置 Grid 布局的列和行的大小。

可以通过grid-row、grid-column 等属性对 Grid 布局中的单元格进行进一步的定位,例如:

1
2
3
4
5

.item {
grid-row: 1 / 3;
grid-column: 2 / 4;
}

在这个例子中,通过 grid-row 和 grid-column 属性设置一个单元格的位置和大小,定义其跨越两行、两列。

CSS Grid 布局的优势

CSS Grid 布局与传统的基于盒模型的布局模型相比,具有以下优势:

  • 更加灵活
    CSS Grid 布局允许同时在行和列方向上对元素进行布局,而且可以通过设置网格行列的名称,自由地定义网格项在网格内部的位置,这使得 CSS Grid 布局更加灵活、精确。

  • 更加简洁
    CSS Grid 布局使得摆放元素的规则非常清晰,只需要设置容器的属性,就能实现所需的布局。与传统的布局模型相比,代码更加简洁,更加容易理解和维护。

  • 更加适应性
    CSS Grid 布局具有强大的适应性,可以根据不同大小的设备和屏幕自动调整布局,适应性比较好,可以方便地实现响应式布局。

属性赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
// grid-template-columns: repeat(5, 20%) 和上一个效果一样
// grid-template-columns: 100px 3em 40% 单位可以混合使用
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 1;
grid-column-end: 4
grid-column-start: span 3;// 延伸宽度几个列单位

//grid-column-end: -2; 也可以赋值负数,从右边开始数
//grid-column2 / 4; 第二列到第三列 左闭右开
grid-column: 2 / span 3 从第二个开始,延伸3个列(234


grid-area: 1 / 2 / 4 / 6; // 直接覆盖一个句型, x1, y1, x2, y2
}
 Comments