css 居中,中央

在我的技巧里,有4中居中中央的方法:

1.position:absolute; top:50%;left:50%; margin : -x 0 0 -x;

这是绝对定位的方法,通过算法移动,坏处就是必须知道element的height & width。

2.vertical align middle

在element 里,只要知道父层的高,子层就能通过vertical align middle移动到中间,当然,父层同时也要有text align center,或者子层margin auto; display:block;

3.在table里

就是table tr td 里的element是可以简单的居中。坏处就是table和tr必须height 100%; width:100%

4.自己模拟table css

5. 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" class="height">
<head>
    <title></title>
    <style>
        *{
            margin:0; 
            height:0;
        }
        .height{
            height:100%;
        }
        .body{
            height:100%;
            background-color:red;
            overflow:hidden;
            text-align:center;
            position: relative;
        }
        .body::after {
            content: "";
            vertical-align: middle;
            display: inline-block;
            width: 1px;
            height: 100%;
        }
        .content{
            display:inline-block;
            vertical-align:middle;
            width:500px;
            background-color:white;
            padding:50px;
            position: relative;
        }
    </style>
</head>
<body class="body">
    <div class="content">asd</div>
</body>
</html>

这也是一样的原理,只是自作了一个after的elem。

 

原文地址:https://www.cnblogs.com/stooges/p/4686408.html