1. 程式人生 > 實用技巧 >css容器內元素垂直水平居中

css容器內元素垂直水平居中

如果容器已知高度且容器內需要元素垂直居中,我們可以給容器內新增一個偽元素,設定這個偽元素高度為100%。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            img{
                width: 60px;
                height: 60px;
            }
.author-image, .author-info{ display: inline-block; } .author-email, .author-name{ display: block; } .author-image,.author-info{ vertical-align: middle; }
.author-meta{ height: 100px; border: 1px solid #ccc; text-align: center; } .author-meta:before{ content: ''; display: inline-block; vertical-align:middle; height
: 100%; } </style> </head> <body> <p class="author-meta"> <img class="author-image" src="img/cat.jpg" > <span class="author-info"> <span class="author-name">sfhufhaisfhiais</span> <a href="" class="author-email">sfasfasfa</a> </span> </p> </body> </html>

效果: