最近在項目中又用到了元素的垂直居中,在這裡整理總結一下可以實作元素垂直居中的幾種方法。
方法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>