1.用margin: 0 auto实现
将父容器设置一个固定宽度width,给居中元素设置margin: 0 auto即可
html
<div class="content">
<div class="div1"></div>
</div>
CSS
.content{
width: 500px;
height:100px;
border: 2px solid black;
}
.div1{
width: 100px;
height: 100px;
background-color: chocolate;
margin: 0 auto;
}
优点:实现简单,浏览器兼容性强
缺点:扩展性差,无法自适应未知情况。
2.设置inline-block与text-align实现
只需将父容器设置text-align,再将居中元素设置inline-block即可实现水平居中
.content{
width: 500px;
height:100px;
border: 2px solid black;
text-align: center;
}
.div1{
width: 100px;
height: 100px;
background-color: aqua;
display: inline-block;
}
优点:简单易懂,扩展性强
缺点:需要额外处理inline-block的浏览器兼容性问题
3.使用绝对定位实现
需将居中元素设置:
position:absolute;
width:宽度值;
left:50%;
margin-left:-(宽度值/2);
案例:
.content{
position: relative;
width: 500px;
height:100px;
border: 2px solid black;
}
.div1{
width: 100px;
height: 100px;
background-color: indianred;
position: absolute;
left: 50%;
margin-left: -50px;
}
需要注意的是,子元素设置绝对定位后,若父元素没有设置定位,那么子元素会继续往上找父元素的父元素,直到找到设置了定位的元素相对其水平居中,若找不到设置了定位的元素,则会相对于body水平居中。因此想要用绝对定位实现水平居中需要将父元素设置定位。
优点:扩展性强,兼容性强;
缺点:理解性难。
4.使用CSS3的flex布局实现
只需将父容器设置display:flex和justify-content:center即可实现水平居中。
.content{
width: 500px;
height:100px;
border: 2px solid black;
display: flex;
justify-content: center;
}
.div1{
width: 100px;
height: 100px;
background-color: violet;
}
优点:实现简单,扩展性强
缺点:兼容性差