前端基础知识之 CSS 实现垂直居中

123 阅读2分钟

从今天开始对本人学过的一些前端的基础知识进行总结补充,希望大家也能在共同学习过程中有所收获。

首先我们讲讲如何在 CSS 中实现垂直居中。而所有方法都基于一个条件,那就是所需要居中的元素的父元素高度是否确定。

如果父元素的高度不确定,即 .parent 的 height 不确定,那么我们只需要在目标元素中加入:

padding: 10px 0; /*给目标元素加 padding,上下为10 px,左右 0*/

如果父元素的高度确定了,那么就要用更复杂的方法:

table

为了实现垂直居中,可以使用 table 的自带属性:

<table class="parent">
    <tr>
        <td class="child">
        所有内容
        </td>
    </tr>
</table>

100% 高度的 after、before 和 inline block

我们也可以在子元素前、后分别用一个 span 占位,然后使两个 span 的相对高度为100%:

HTML 部分:
<div class"parent">
    <span class="before"></span>
        <div class="child">
            所有内容
        </div>
     <span class="after"></span>
 </div>
 
 
 CSS 部分:
 .parent{
     height: 600px; /*高度确定*/
     text-align:center;
 }
 .child{
     display:inline-block;
     width:300px;
     vertical-align:middle;
 }
 .parent .before{
     display:inline-block;
     height:100%;
     vertical-align:middle;
 }
 .parent .after{
     display:inline-block;
     height:100%;
     vertical-align:middle;
 }        

当然,两个 span 也可以使用更高级的伪元素实现,只需要让伪元素的 content='',其余操作几乎相同。

div 展示为 table

我们也可以使用一个技巧,那就是将 div 元素展示成 table,那就一样可以使用 table 的属性。

HTML 部分:
<div class="table">
    <div class="td">
        <div class="child">
        所有内容
        </div>
    </div>
</div>

CSS 部分:
div.table{
    display: table;
    height:600px;
}
div.td{
    display: table-cell;
    vertical-align:middle;
}

margin-top -50%

也可以在父元素上相对定位,让子元素绝对定位并调整 margin-top,但是这种方法需要手动计算:

HTML部分:
<div class"parent">
    <div class="child">
        所有内容
    </div>
 </div>
 
 CSS部分:
 .parent{
     height:600px;
     position:relative;
 }
 .child{
     width:300px;
     position:absolute;
     top:50%;
     left:50%;
     margin-left:-150px;
     height:100px;
     margin-top:-50px;
 }   

translate -50%

还有就是最常用的 transform 的 translate,就不需要我们手动计算:

HTML部分:
<div class"parent">
    <div class="child">
        所有内容
    </div>
 </div>
 
 CSS部分:
 .parent{
     height:600px;
     position:relative;
 }
 .child{
     width:300px;
     position:absolute;
     top:50%;
     left:50%;
     transform:translate(-50%, -50%);
 }

absolute margin auto

也可以在绝对定位的前提下,让 margin 处于 auto 的状态:

HTML部分:
<div class"parent">
    <div class="child">
        所有内容
    </div>
 </div>
 
 CSS部分:
 .parent{
     height:600px;
     position:relative;
 }
 .child{
     width:300px;
     height:200px;
     position:absolute;
     margin:auto;
     top:0;
     left:0;
     bottom:0;
     right:0;
 }

flex 布局

最后还可以使用 flex 布局的特性:

HTML部分:
<div class"parent">
    <div class="child">
        所有内容
    </div>
 </div>
 
 CSS部分:
 .parent{
     height:600px;
     display:flex;
     justify-content:center;
     align-items:center;
 }
 .child{
     width:300px;
 }

最后

其实还有很多方法可以实现垂直居中,本文主要参考了《七种方式实现垂直居中》

©本总结教程版权归作者所有,转载需注明出处