用margin:auto;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
width:100px;
height:100px;
background-color: yellow;
复制代码
用transform或margin-left、margin-top
position:absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);
// 还有一种:
// margin-left: -content_w/2;
// margin-top: -content_h/2;
// 此种方法要获得盒子的宽度和高度
width:100px;
height:100px;
background-color: yellow;
复制代码
还有一种inline-block+vertical-align:middle;和盒子基线什么的有关,有一些缺点,有点事不确定height也能居中;
.container{
width: 200px;
height: 200px;
text-align: center;
background-color: red;
}
.container::before{
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.item{
display: inline-block;
vertical-align: middle;
width: 100px;
height: 100px;
background-color: yellow;
}复制代码