css实现元素垂直居中的方法
1.在不知道自己的高度和父元素高度的情况下,使用定位+平移:
.parent {
position: relative;
}
.son {
position :absolute;
top: 50%;
transform: translateY(-50%);
}
2.若父容器下只有一个元素,且已知父元素高度,使用相对定位即可:
.parent {
height: 400px;
}
.son {
position: relative;
top: 50%;
transform: translateY(-50%);
}
3.在不考虑老式浏览器兼容性的的情况下,可以使用flex布局(弹性布局):
css:
.container{
width: 300px;
height: 200px;
border: 3px solid #546461;
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
.inner{
border: 3px solid #458761;
padding: 20px;
}
4.margin:auto法
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;
}
html
<div>
<img src="01.png">
</div>