flex布局中如何让子元素水平垂直居中
思路:
- 先让子元素在主轴上居中对齐:justify-content: center;
- 再让子元素在侧轴上居中对齐:align-items: center;(单行) 或者 align-content: center;(多行)
注意:不要忘了给父元素添加display:flex;,这是开启 flex 布局的钥匙
举例说明:
单行子元素实现水平垂直居中:
<div>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
<style type="text/css">
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
justify-content: center;
align-items: center;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
margin: 0 10px;
}
</style>
运行结果:
多行子元素实现水平垂直居中:
<div>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
</div>
<style type="text/css">
div{
display: flex;
width: 800px;
height: 400px;
background-color: orange;
flex-wrap: wrap;
justify-content: center;
align-content: center;
}
div span{
width: 150px;
height: 100px;
background: skyblue;
margin: 10px;
}
</style>
运行结果: