考察知识:
flex布局 + 水平垂直居中的实现
初始效果
代码关键:给父盒子添加以下属性
flex-wrap: wrap; /* 允许换行 */
justify-content: space-around; /* 主轴对齐方式 */
align-content: space-around; /* 多行在侧轴上的对齐方式 */
<!DOCTYPE html>
<html lang="zn-ch">
<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>flex九宫格</title>
</head>
<body>
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
</body>
<script></script>
<style lang="scss">
.box {
width: 400px;
height: 400px;
border: 1px solid red;
display: flex; /* */
flex-wrap: wrap; /* 允许换行 */
justify-content: space-around; /* 主轴对齐方式 */
align-content: space-around; /* 多行在侧轴上的对齐方式 */
.item {
width: 100px;
height: 100px;
background-color: pink;
border: 1px solid red;
}
}
</style>
</html>
优化:每个小盒子的内容水平垂直居中
<body>
<div class="box">
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
<div class="item">
<div class="pink"></div>
item-name
</div>
</div>
</body>
<script></script>
<style lang="scss">
.box {
width: 400px;
height: 400px;
border: 1px solid red;
display: flex; /* */
flex-wrap: wrap; /* 允许换行 */
justify-content: space-around; /* 主轴对齐方式 */
align-content: space-around; /* 多行在侧轴上的对齐方式 */
.item {
width: 100px;
height: 100px;
background-color: skyblue;
border: 1px solid red;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
.pink {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: pink;
}
}
}
</style>