垂直居中,是前端的基本操作,我主要在兩種情況下進行簡單的實現。分別為:
- 已知高度(指自身高度)
- 未知高度
簡單的html代碼如下:
<style>
div.father{
height: 300px;
width: 500px;
border: 1px solid red;
}
</style>
<div class="father">
<div class="child">123</div>
</div>
- 未知高度時
- 1.通過 display:table-cell 實現(此方法針對 img 在 div 標簽中垂直居中很適用)
div.father{
display: table-cell;
vertical-align: middle;/*IE8 及以上*/
}
- 2.通過transform: translateY(-50%) 實現
div.father{
position: relative;
}
div.child{
position: absolute;
top: 50%;
transform: translateY(-50%);/* CSS3 */
}
- 已知高度時
- 1.通過 margin-top 實現
div.father{
position: relative;
}
div.child{
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}
- 2.最后是一種比較特別的情況,當 .child 中的內容不超過一行時,通過設置 height = line-height 也可實現垂直居中
div.child{
height: 300px;
line-height: 300px;
}
以上,是簡單的總結,兼容性方面也很差,方法還有很多。