如果.parent的height不写,要让.child垂直居中,只需要padding:10px 0 即可;
如果.parent的height写死了,很难把.child垂直居中,需要用到一下7种方法;
(能不写height就不写height)
1.table自带功能,td自己就能垂直居中
<table class="parent"> <tr> <td class="child"> </td> </tr> </table>
2.parent包裹着三个部分:span div span ,span分别为before和after,给两个span设置高度100%,display inline-block
<div class="parent"> <span class=before></span> <div class="child"> 一串文字一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字一串文字 </div> <span class=after></span> </div>
.parent{ border: 3px solid red; height: 600px; text-align: center; } .child{ border: 3px solid black; display: inline-block; width: 300px; vertical-align: middle; } .parent .before{ outline: 3px solid red; display: inline-block; height: 100%; vertical-align: middle; } .parent .after{ outline: 3px solid red; display: inline-block; height: 100%; vertical-align: middle; }
3.div装成table
三层div嵌套,最外层到内层class分别为:table-td-child
<div class="table"> <div class="td"> <div class="child"> 一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字 </div> </div> </div>
div.table{ display: table; border: 1px solid red; height: 600px; }
div.td{ display: table-cell; border: 1px solid blue; vertical-align: middle; }
.child{ border: 10px solid black; }
4.父亲相对定位,子元素绝对定位,上左50%
<div class="parent"> <div class="child"> 一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字 一串文字一串文字一串文字一串文字 </div>
</div>
.parent{ height: 600px; border: 1px solid red; position: relative; } .child{ border: 1px solid green; width: 300px; position: absolute; top: 50%; left: 50%; margin-left: -150px; height: 100px; margin-top: -50px; }
5.position:absolute
top:50%
left:50%
transform:translate(-50%,-50%)
6.position:absolute
margin:auto
7.display:flex
justify-content:center //内容对其,弹性项沿弹性容器的主轴线对齐,center:弹性项目居中紧挨着填充
align-items:center // 设置弹性盒子在纵轴方向上的对齐方式,center:侧轴居中