最近在项目中又用到了元素的垂直居中,在这里整理总结一下可以实现元素垂直居中的几种方法。
方法1:
利用line-height实现单行元素的垂直居中。
实现方法:将行内文本的line-height设置为父级元素的高度:
<body>
<div id='parent'>
<p id='child'>文本垂直居中</p>
</div>
</body>
<style>
#parent{
border:1px solid blue;
width:200px;
height:200px;
text-align: center;
background-color:gray;
}
#child{
line-height:200px;
}
</style>
方法2:
父级设置display:table,子元素 display:table-cell;vertical-align:middle;
实现方式:
<body>
<div id='parent'>
<div id='child'>文本垂直居中</div>
</div>
</body>
<style>
#parent{
border:1px solid blue;
width:200px;
height:200px;
text-align: center;
display:table;
background-color:gray;
}
#child{
display:table-cell;
vertical-align: middle;
}
</style>
方法3:
利用margin:auto
实现方式:子元素的设置top,bottom,left,right为0,margin设置为auto,当子元素尝试向父元素的四个方向的距离为0时,自身的宽高不够,剩余部分利用margin:auto自动填充,从而实现垂直水平居中。
<body>
<div id='parent'>
<div id='child'>文本垂直居中文本垂直居中文本垂直居中</div>
</div>
</body>
<style>
#parent{
border:1px solid blue;
background-color:gray;
width:200px;
height:200px;
position:relative;
}
#child{
position:absolute;
margin:auto;
border:1px solid yellow;
left:0px;
right:0px;
top:0px;
bottom:0px;
width:100px;
height:100px;
}
</style>
方法4:
利用translate位移属性:
实现方式:将top,left分别设置50%,相对于父元素偏移一半,然后设置自身的位移为-50%,-50%,设置自身反方向偏移一半。
<body>
<div id='parent'>
<div id='child'>垂直居中</div>
</div>
</body>
<style>
#parent{
border:1px solid blue;
background-color:gray;
width:200px;
height:200px;
position:relative;
}
#child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
-ms-transform:translate(-50%,-50%); /* IE 9 */
-webkit-transform:translate(-50%,-50%); /* Safari and Chrome */
}
</style>
方法5:
利用display:flex; justify-content:center; align-items:center;
实现方式:
<body>
<div id='parent'>
<div id='child'>垂直居中</div>
</div>
</body>
<style>
#parent{
border:1px solid blue;
background-color:gray;
width:200px;
height:200px;
display:flex;
justify-content:center;
align-items:center;
}
#child{
}
</style>
方法6:
利用margin设置偏移量:
实现方式:通过百分比设置子元素的宽和高,通过计算偏移量得出使子元素居中的距离。
<body>
<div id='parent'>
<div id='child'>垂直居中</div>
</div>
</body>
<style>
#parent{
border:1px solid blue;
background-color:gray;
width:200px;
height:200px;
position: relative;
}
#child {
border:1px solid yellow;
position: absolute;
top: 50%;
left: 50%;
height: 30%;
width: 50%;
margin: -15% 0 0 -25%;
}
</style>