css 网格布局
最编程
2024-07-13 13:58:30
...
概述
目前css布局方案中,网格布局可以算得上是最强大的布局方案了。它可以将网页分为一个个网格,然后利用这些网格组合做出各种各样的布局。
基本概念
在学习grid布局之前,我们需要了解一些基本概念
1.容器和项目
采用网格布局的区域,称为“容器”。容器内部的采用网格定位的子元素称为“项目”
<div class="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
上面的代码中,wrapper就是容器,item就是项目
1.1 行、列和单元格
容器里面的水平区域称为“行”,垂直区域称为“列”,行列重叠出来的空间组成单元格
1.2 网格线
划分网格的线,称为”网格线“
黄色的代表是列的网格线,绿色代表的是行的网格线
Grid和flex类似,布局的属性都是分为两类,一类定义在容器上,称为容器属性,一类定义在项目上,称为项目属性
2 容器属性
2.1 display属性
display:grid指定一个容器为网格布局
完整代码(复制过去就可以使用)
<!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>
.wrapper {
width: 450px;
background: #f3f3f3;
text-align: center;
/* 定义属性 */
+ display: grid;
/* 设置列的宽度 */
+ grid-template-columns: 110px 190px 150px;
/* 设置行的高度 */
+ grid-template-rows: 50px 150px 150px
}
.item {
text-align: center;
border: 1px solid #fff;
color: #fff;
font-weight: bold;
/* line-height: 150px; */
}
.item:first-of-type {
background: #ef342a
}
.item:nth-of-type(2) {
background: #00a0a0;
}
.item:nth-of-type(3) {
background: #a0a0ff;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
</body>
</html>
在这里我定义的三个网格都是宽高为150px
当然啦,我们也可以把它定义为行内元素,该元素内部就采用网格布局
2.2 display:inline-grid效果
grid效果
inline-grid效果
完整代码
<!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>
.wrapper {
width: 450px;
background: #f3f3f3;
text-align: center;
/* 定义属性 */
- /* display: grid; */
+ display: inline-grid;
/* 设置列的宽度 */
grid-template-columns: 110px 190px 150px;
/* 设置行的高度 */
grid-template-rows: 50px 150px 150px
}
.item {
text-align: center;
border: 1px solid #fff;
color: #fff;
font-weight: bold;
/* line-height: 150px; */
}
.item:first-of-type {
background: #ef342a
}
.item:nth-of-type(2) {
background: #00a0a0;
}
.item:nth-of-type(3) {
background: #a0a0ff;
}
</style>
</head>
<body>
+ <span>foo</span>
<div class="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
+ <span>bar</span>
</body>
</html>
3 grid-template-columns和 grid-template-rows
grid-template-columns:用来指定行的宽度
grid-template-rows:用来指定行的高度
.wrapper{
width:450px;
background: #e5e5e5;
text-align:center;
display: inline-grid;
grid-template-columns: 150px 150px 150px;
grid-template-rows: 150px 150px 150px
}
上面这段代码指定的宽高各为150px
当然来,出来能指定具体的数值之外,也可以使用百分比来表示
.wrapper {
display: grid;
grid-template-columns: 33.33% 33.33% 33.33%;
grid-template-rows: 33.33% 33.33% 33.33%;
}
3.1 repeat
有时候,重复写同样的值非常麻烦,尤其网格很多时。这时,可以使用repeat()
函数,简化重复的值。上面的代码用repeat()
改写如下
.wrapper {
display: grid;
grid-template-columns: repeat(3, 33.33%);
grid-template-rows: repeat(3, 33.33%);
}