简单地说,CSS Grid布局就是一个二维的基于网格的布局系统,它可以同时处理列(Columns)和行(rows),目标是改变我们基于网格设计的用户接口方式。
通过简单的Grid 布局例子来熟悉它:
<div class="container">
<!-- 先写一行,在行中再定义列 -->
<!-- 一等份 -->
<div class="row">
<span class="item col-12">12列</span>
</div>
<!-- 二等份 -->
<div class="row">
<span class="item col-6">6列</span>
<span class="item col-6">6列</span>
</div>
<!-- 三等份 -->
<div class="row">
<span class="item col-4">4列</span>
<span class="item col-4">4列</span>
<span class="item col-4">4列</span>
</div>
<!-- 二等份: 2: 10 -->
<div class="row">
<span class="item col-2">2列</span>
<span class="item col-10">10列</span>
</div>
</div>
grid.css文件
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100vw;
height: 100vh;
display: grid;
place-content: center;
}
.container {
min-width: 80vw;
display: grid;
gap: 0.5em;
}
.container > .row {
display: grid;
/* 任何一行都是由12列组成 */
grid-template-columns: repeat(12, 1fr);
min-height: 3em;
gap: 0.5em;
}
.container > .row > .item {
padding: 1em;
background-color: lightcyan;
border: 1px solid;
}
.col-12 {
grid-area: auto / span 12;
}
.col-11 {
grid-area: auto / span 11;
}
.col-10 {
grid-area: auto / span 10;
}
.col-9 {
grid-area: auto / span 9;
}
.col-8 {
grid-area: auto / span 8;
}
.col-7 {
grid-area: auto / span 7;
}
.col-6 {
grid-area: auto / span 6;
}
.col-5 {
grid-area: auto / span 5;
}
.col-4 {
grid-area: auto / span 4;
}
.col-3 {
grid-area: auto / span 3;
}
.col-2 {
grid-area: auto / span 2;
}
.col-1 {
grid-area: auto / span 1;
}