CSS垂直居中的四种方法

1.margin:auto 法:

html:

<div>
<img src="mm.jpg">
</div>

css:

div{
width:400px;
height:400px;
position:relative;
border:1px solid #465468;
}
img{
position:absolute;
margin:auto;
top:0;
left:0;
right:0;
bottom:0;
}

定位为上下左右为0,margin:0可以实现脱离文档流的居中

2.margin负值法

.container{
width:500px;
height:500px;
border: 2px solid #379;
position:relative;
}

,inner{
width:480px;
height:480px;
background-color:#746;
position:absolute;
top:50%;
left:50%;
margin-top:-190px;
margin-left:-240px;
}

可以将负值替换成

transform:translateX(-50%)
transform:translateY(-50%)

3.table-cell(未脱离文档流)

4.利用flex

发布了158 篇原创文章 · 获赞 44 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43277404/article/details/103949648