垂直居中

2019-08-26  本文已影响0人  逆风飘游的鱼

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: 负的高度一半;}

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;}

上一篇 下一篇

猜你喜欢

热点阅读