Grid 与 Flex 布局有一定的相似性,但是功能更加强大,学习起来也有不少难度,不过相信下面的内容会帮你更快的掌握 Grid。 1. 官方定义通过设置 display: grid; 可以定义一个 CSS 网格。然后使用 grid-template-rows 和 grid-template-columns 属性来定义网格的 columns 和 rows。 2. 解释Grid 是一个二维网格布局,它有行 grid-template-rows (横排)、 列 grid-template-columns(竖排),内部的项目就分布在其中,而网格线就是行和列划分出来的。 基本属于解释: 容器:上面代码中,最外层的<div>元素demo就是容器。 3. 语法
.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 的缩写 项目包含属性介绍
4. 兼容性
5. 实例本小节暂时不对父容器和子容器内的属性进行详细的实例使用展示,仅对 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>
<Meta charset="UTF-8">
<Meta 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>
<Meta charset="UTF-8">
<Meta 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>6. 小结
|