这里分享几个常用的例子,其他的具体的就参考 https://www.runoob.com/css3/css3-flexbox.html
完美居中(水平垂直居中)
举个例子:
CSS:
.flex-container {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 250px;
background-color: lightgrey;
}
HTML:
<div class="flex-container">
<div>盒子</div>
</div>
效果图:
均匀分布(space-around),两端对齐(space-between)(水平方向)
举个例子:
CSS:
.flex-container {
display: flex;
justify-content: space-around; //均匀分布(两端对齐属性改为space-between,其他属性可以参考上面的的w3c链接)
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item{
width:50px;
height:50px;
background-color: red;
}
HTML:
<div class="flex-container">
<div class="flex-item">盒子1</div>
<div class="flex-item">盒子2</div>
<div class="flex-item">盒子3</div>
</div>
均匀分布效果图:
两端对齐效果图:
均匀分布,两端对齐(上下对齐)(垂直方向)
默认是水平方向,也就是所谓的X轴,我们想要在垂直方向
使用justify-content进行布局就这个时候就需要用到flex-direction属性将X轴改为Y轴(竖直方向)
举个例子:
CSS:
.flex-container {
display: flex;
flex-direction: column;
justify-content: space-around;(同理两端对齐属性改为space-between)
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item{
width:50px;
height:50px;
background-color: red;
}
HTML:
<div class="flex-container">
<div class="flex-item">盒子1</div>
<div class="flex-item">盒子2</div>
<div class="flex-item">盒子3</div>
</div>
均匀分布效果图:
两端对齐(上下对齐)效果图:
多个盒子水平垂直居中布局
举个栗子:
CSS:
.flex-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item{
width:50px;
height:50px;
}
HTML:
<div class="flex-container">
<div class="flex-item">盒子1</div>
<div class="flex-item">盒子2</div>
<div class="flex-item">盒子3</div>
</div>
效果图:
多个盒子栅格布局(每行固定盒子个数)
html代码
<div class="flex-container">
<div class="flex-item">盒子1</div>
<div class="flex-item">盒子2</div>
<div class="flex-item">盒子3</div>
<div class="flex-item">盒子4</div>
<div class="flex-item">盒子5</div>
<div class="flex-item">盒子6</div>
<div class="flex-item">盒子7</div>
<div class="flex-item">盒子8</div>
<div class="flex-item">盒子9</div>
</div>
css代码
.flex-container{
dispaly: grid; // 启用栅格布局
grid-template-columns: repeat(5, 1fr); 每行盒子个数为5
background-color: lightgrey;
}
.flex-item{
background-color: red;
width:50px;
height:50px;
}
觉得有用的童鞋给作者点个赞再走呗!蟹蟹!