1、margin:auto
div{
width: 40Opx;
height: 400px;
position: relative;
border: 1px solid #465468;
}
img{
position: absolute;
margin: auto;
top: 0;
left:O;
right: O;
bottom: O;
}
定位为上下左右为0, margin: 0可以实现脱离文档流的居中
2、margin负值法
.container{
width: 50Opx;
height: 400px;
border: 2px solid #379;
position: relative;
}
.inner{
width: 480px;
height: 380px;
background-color: #746;
position: absolute;
top:50%;
left: 50%;
margin-top: -190px;/*height的一半*/
margin-left:-240px;/*width 的一半*/
}
补充:其实这里也可以将marin-top和 margin-left负值替换成,transform: translateX(-50%)和l transform: translateY(-50%)
3、利用flex将父元素设置为display:flex,并且设置align-items:centersjustify-content:center;
.container{
width: 300px;
height: 200px;
border: 3px solid #546461;
display: flex;
align-items: center;
justify-content: center;
}
.inner{
border: 3px solid #458761;
padding: 20px;
}