用margin和定位实现垂直居中

<!DOCTYPE html>
<html>
    <head>
        <title>居中</title>
        <style type="text/css">
            .parent{
                width:100px;
                height:80px;
                /*父元素需设置position:relative/absolute/fixed;*/
                position:relative;
                background: #eee;
            }
            .children{
                background:green;
                /*子元素的宽高可以是具体值,也可以是百分比,but不可以是auto*/
                width:50px;
                height:50px;
                margin:auto;
                position: absolute;
                top:0;
                left:0;
                right:0;
                bottom:0;
            }
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="children">啦啦啦啦</div>
        </div>
    </body>
</html>

截图如下:

《用margin和定位实现垂直居中》

    原文作者:雨花石
    原文地址: https://segmentfault.com/a/1190000009999859
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞