用grid实现
用grid实现,只需要在容器上声明为grid容器,并且设置行列的宽度分片三个1fr,设置列的间距gap间距就ok了
三步骤
- 声明grid容器;
- 设置使用分片设置列宽,行也可以省略,那样就变成更自适应了,不再限制于九个元素;
- 设置gap,行列的间距
```css
/ grid实现 /
container-grid {
display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; grid-row-gap: 20px; grid-column-gap: 20px; }
<a name="vnEeY"></a>
### flex实现比较麻烦
需要用margin控制间距,并在容器上设置便宜,让最左边和最上边的元素多余的margin切去。容器内元素的宽度也需要计算,好在也不是太难,也不需要js控制。<br />具体步骤:
- 容器声明flex,设置容器内元素可以换行
- 设置元素的margin-top和margin-left做间距效果
- 用css计算属性计算元素的宽度
- 设置容器的margin-top和margin-left把最左边和最上边多余的margin切去
```css
/* flex实现 */
#container-flex {
display: flex;
flex-wrap: wrap;
margin-top: -20px;
margin-left: -20px;
}
.item-flex {
font-size: 4em;
text-align: center;
width: calc((100% - 60px) / 3);
margin-top: 20px;
margin-left: 20px;
}
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
margin: 0;
padding: 0;
background-color: black;
box-sizing: border-box;
}
.item {
font-size: 4em;
text-align: center;
}
.item-1 {
background-color: #ef342a;
}
.item-2 {
background-color: #f68f26;
}
.item-3 {
background-color: #4ba946;
}
.item-4 {
background-color: #0376c2;
}
.item-5 {
background-color: #c077af;
}
.item-6 {
background-color: #f8d29d;
}
.item-7 {
background-color: #b5a87f;
}
.item-8 {
background-color: #d0e4a9;
}
.item-9 {
background-color: #4dc7ec;
}
/* grid实现 */
#container-grid {
border: 0px solid red;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-row-gap: 20px;
grid-column-gap: 20px;
}
/* flex实现 */
#container-flex {
display: flex;
flex-wrap: wrap;
margin-top: -20px;
margin-left: -20px;
}
.item-flex {
font-size: 4em;
text-align: center;
width: calc((100% - 60px) / 3);
margin-top: 20px;
margin-left: 20px;
}
</style>
</head>
<body>
<div id="container-flex">
<div class="item-flex item-1">1</div>
<div class="item-flex item-2">2</div>
<div class="item-flex item-3">3</div>
<div class="item-flex item-4">4</div>
<div class="item-flex item-5">5</div>
<div class="item-flex item-6">6</div>
<div class="item-flex item-7">7</div>
<div class="item-flex item-8">8</div>
<!-- <div class="item-flex item-9">9</div> -->
</div>
<h1 style="color: #fff">flex实现</h1>
<br />
<br />
<hr />
<br />
<br />
<div id="container-grid">
<div class="item item-1">1</div>
<div class="item item-2">2</div>
<div class="item item-3">3</div>
<div class="item item-4">4</div>
<div class="item item-5">5</div>
<div class="item item-6">6</div>
<div class="item item-7">7</div>
<div class="item item-8">8</div>
<!-- <div class="item item-9">9</div> -->
</div>
<h1 style="color: #fff">grid实现</h1>
</body>
</html>
参考
css计算属性
https://developer.mozilla.org/zh-CN/docs/Web/CSS/calc())