垂直居中

关于垂直居中的方法已经老生常谈了,这里只记录下自己最近发现的垂直居中方法。

1、通过vertival-align:middle:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        .wrap{
            width: 1000px;
            height: 500px;
            margin: 0 auto;
            text-align: center;
            border: 1px solid #ccc;
        }
        .text{
            vertical-align: middle;
        }
        .text:before{
            content: '';
            display: inline-block;
            width: 1px;
            height: 100%;
            margin-left: -1px;
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <span class="text">it is a word</span>
    </div>
</body>
</html>

这种方法是通过元素与伪元素设置vertical-align:middle来实现的,很多朋友对这个属性都是一知半懂,可以看看这位大神的文章:http://www.zhangxinxu.com/wordpress/2010/05/我对css-vertical-align的一些理解与认识(一)/

2、通过绝对定位与margin:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .wrap{
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            width: 500px;
            height: 300px;
            border: 1px solid #ccc;
            margin: auto
        }
    </style>
</head>
<body>
    <div class="wrap">is is a word</div>
</body>
</html>

这个就不必多说了,太基础。

3、通过table-cell实现。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        div{
            display: table-cell;
            height: 10em;
            border: 1px solid #ccc;
            vertical-align: middle;
        }
        span{
            display: inline-block;
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <div>
        <span>这是一个关于多行文字的垂直居中<br>这是第二行</span>
    </div>
</body>
</html>

还有很多方法可以实现,比如通过表格之类的。

原文地址:https://www.cnblogs.com/11lang/p/6617058.html