https://jscode.me/t/topic/1936
如果 .parent 的 height 不寫,你只需要 padding: 10px 0; 就能將 .child 垂直居中;
如果 .parent 的 height 寫死了,就很難把 .child 居中,以下是垂直居中的方法。
忠告:能不寫 height 就千萬別寫 height。
1.table自帶功能
<table class="parent">
? ? <tr>? ? ? <td class="child">? ? 一串文字一串文字一串文字一串文字? ? </td>? ? </tr>
? </table>
.parent{? height: 600px;}
2.div 裝成 table
<div class="table">
<div class="td"> <div class="child">一串文字一串文字一串文字 </div></div>
? </div>
div.table{? display: table;? height: 600px;}
div.td{? display: table-cell;? vertical-align: middle;}
3.margin-top -50%
<div class="parent">? <div class="child">一串文字一串文字</div>? </div>
.parent{ height: 600px;? position: relative;}
.child{? ?position: absolute;? top: 50%; margin-top: 負(fù)的高度一半;}
4.translate -50%
<div class="parent"> <div class="child">? 一串文字一串文字 </div></div>
.parent{ height: 600px;? position: relative;}
.child{? position: absolute;? top: 50%; transform: translateY(-50%);}
5.absolute margin auto
<div class="parent"> <div class="child">? 一串文字一串文字 </div></div>
.parent{? height: 600px; position: relative;}
.child{? position: absolute;? height: 200px;? margin: auto;? top: 0;? bottom: 0;? left: 0;? right: 0;}
6.flex
<div class="parent"> <div class="child">? 一串文字一串文字 </div></div>
.parent{? height: 600px;? display: flex;? justify-content: center;? align-items: center;}