div居中方法4

​​​​​​利用绝对位置 margin 自动 其余四个方向为 0

子元素div是绝对定位,所以需要父元素设置为position: relative;

单独使用 margin:auto;   不可以

需要联合使用  position: absolute;margin:auto; top: 0;left: 0;right: 0;bottom: 0;

外边距自动,四个方向都是 填满状态

<html>
    <head>
        <meta charset="UTF-8">
        <title>居中4</title>
    </head>
    <body>
    <style>
        .fu{
            width: 200px;
            height: 200px; 
            border: 1px solid #000000;
            position: relative;
        }
        .zi{
             width: 40px ;
              height: 40px;
              background-color: green;
              position: absolute;
              margin: auto;
              top: 0;
              left: 0;
              bottom: 0;
              right: 0;
        }
    </style>
        <div class="fu">
            <div class="zi"></div>
        </div>

    </body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_36836332/article/details/81592681