元素居中方法总结

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

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>

猜你喜欢

转载自www.cnblogs.com/huwt/p/10947197.html