通过定位实现子元素相对于父元素上下左右居中


absolute定位有一个很常用的用途,就是当希望子元素在父元素的正中央时,可以这样操作:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{
            width: 500px;
            height: 500px;
            background: blue;
            position: absolute;
            top: 100px;
            left: 100px;
        }
        .son{
            width: 100px;
            height: 100px;
            background: black;
            position: absolute;
            left: 0;  /* 注意不要漏了上下左右为0,否则不会成功 */
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="son"></div>
    </div>
</body>
</html>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM