Grid 布局简介
Grid 与 Flex 布局有一定的相似性,但是更加强大,学习起来也有不少难度,不过相信下面的会帮你更快的掌握 Grid。
通过设置 display: grid;
可以定义 CSS 网格。然后使用 grid-template-rows
和 grid-template-columns
来定义网格的 columns
和 rows
。
使用这些定义的网格被描述为 显式网格 (explicit grid)。
参考文献:MDN
Grid 是二维网格布局,它有行 grid-template-rows
(横排)、 列 grid-template-columns
(竖排),内部的项目就分布在其中,而网格线就是行和列划分出来的。
基本属于解释:
容器:上面中,最外层的<div>元素demo
就是容器。
项目:内层的三个<div>元素item
就是项目。
行:把 row
即横向称为行,
列:把column
即纵向称为列。
单元格:它们的交叉区域cell
也就是单元格。
网格线:grid line
网格线就是由行和列划分出来的。
.demo{
display:grid
}
.demo{
display:inline-grid;
}
容器包含如下
grid-template
是 grid-template-columns
、grid-template-rows
、 grid-template-areas
缩写。
grid
是 grid-template-rows
、grid-template-columns
、grid-template-areas
、 grid-auto-rows
、grid-auto-columns
、grid-auto-flow
的合并缩写。
:gird 很复杂因此不推荐 grid
的缩写
项目包含介绍
本小节暂时不对和子容器内的进行详细的实例使用展示,仅对 display
进行区分,可以从下一小节开始其他的学习。
<div class="demo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
通过下面的设置:
.demo{
display: grid;
grid-template-columns:px px;
grid-template-rows:px px;
border:px solid #eee
}
.item:nth-of-type(1){
background: red;
}
.item:nth-of-type(2){
background: green;
}
.item:nth-of-type(3){
background: purple;
}
图
<!DOCTYPE html>
<html lang="en">
<head>
< charset="UTF-8">
< name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.demo{
display: grid;
grid-template-columns:px px;
grid-template-rows:px px;
border:px solid #eee
}
.item:nth-of-type(1){
background: red;
}
.item:nth-of-type(2){
background: green;
}
.item:nth-of-type(3){
background: purple;
}
</style>
</head>
<body>
<div class="demo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
网学习
</body>
</html>
<div class="demo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
网学习
.demo{
display: inline-grid;
grid-template-columns:px px;
grid-template-rows:px px;
border:px solid #eee
}
.item:nth-of-type(1){
background: red;
}
.item:nth-of-type(2){
background: green;
}
.item:nth-of-type(3){
background: purple;
}
图
<!DOCTYPE html>
<html lang="en">
<head>
< charset="UTF-8">
< name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.demo{
display: inline-grid;
grid-template-columns:px px;
grid-template-rows:px px;
border:px solid #eee
}
.item:nth-of-type(1){
background: red;
}
.item:nth-of-type(2){
background: green;
}
.item:nth-of-type(3){
background: purple;
}
</style>
</head>
<body>
<div class="demo">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
网学习
</body>
</html>