水平居中
1. 行内元素
若是行内元素,给其父元素设置 text-align:center
即可实现行内元素水平居中
<div class="parent">
<span class="child">测试</span>
</div>
<style>
.parent {
background-color: aqua;
text-align: center; /* 水平居中 */
}
.child {
color: #fff;
background-color: blueviolet;
}
</style>
2. 块级元素
2.1 宽高固定
当宽高固定时,以下 html 示例:
<div class="parent">
<div class="child"></div>
</div>
<style>
.parent {
height: 100px;
background-color: aqua;
}
.child {
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
以下四种方式显示效果均为:
方式一:margin:0 auto
<style>
.child {
margin:0 auto;
}
</style>
方式二:absolute + margin-left
<style>
.child {
position: absolute;
margin-left: -50px;
left: 50%;
}
</style>
方式三:absolute + calc
<style>
.child {
position: absolute;
left: calc(50% - 50px);
}
</style>