通過定位實現子元素相對於父元素上下左右居中


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