效果:
<div class="outer">
<div class="inner">oooo.oooo</div>
</div>
1、flex弹性布局
外层容器设置flex弹性布局,设置主轴和交叉轴center
<style>
.outer{
width: 200px;
height: 200px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
width: 100px;
height: 100px;
background-color: pink;
}
</style>
2、绝对定位 + 相对定位 + margin
设置需要内层元素绝对定位,上下左右为0,margin:auto
<style>
.outer{
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.inner{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
3、绝对定位 + 相对定位 + margin / transform
使用margin、transform其中一种即可
<style>
.outer{
width: 200px;
height: 200px;
background-color: skyblue;
position: relative;
}
.inner{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
/* 方式1:利用margin回移自身宽高的50% */
margin-top: -50px;
margin-left: -50px;
/* 方式2:利用translate回移 */
transform: translate(-50%,-50%);
}
</style>
4、设置为行内块 + text-align: center + vertical-align: middle
需要添加伪元素,并设置高度100%,然后利用行内元素居中的方式设置水平垂直居中
<style>
.outer{
width: 200px;
height: 200px;
background-color: skyblue;
text-align: center;
}
.outer::after{
display: inline-block;
content: '';
width: 0;
height: 100%;
vertical-align: middle;
}
.inner{
background-color: pink;
display: inline-block;
vertical-align: middle;
}
</style>