元素居中的一种特殊方法

通过给需要居中的元素加入如下属性:使用此种方法,该元素会相对第一个具有定位环境的父元素居中

position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .fat{
            width: 500px;
            height: 500px;
            border: solid 1px black;
            position: relative;
        }
        .sub{
            width: 100px;
            height: 100px;
            border: solid 1px red;
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }
    </style>
</head>
<body>
    <div class="fat">
        <div class="sub"></div>
    </div>
</body>
</html>

 

posted @ 2019-05-30 00:04  路漫漫我不畏  阅读(160)  评论(0编辑  收藏  举报