如何用定位的方法使盒子垂直左右居中


1.定位有以下幾種:絕對定位,相對定位,fixed定位等

2.fixed定位是針對於整個頁面來說的,浮動於定點處,不適合,相對定位針對的是本來自己的位置,也不適合做相對於父元素的垂直左右居中,我們要用的是絕對定位
3.案例

先創建一個父盒子,一個子盒子:

 
         
<body>
<div class="father">
<div class="son">

</div>

</div>
 
</body>
<style>
.father{
width: 500px;
height: 500px;
">grey;
}
.son{
width: 100px;
height: 100px;
">red;
}
</style>
 

然后得到一個這樣的圖片

 

 最后利用絕對定位來做:

<body>
    <div class="father">
        <div class="son">

        </div>

    </div>
    
</body>
<style>
    .father{
        position: relative;
        width: 500px;
        height: 500px;
        background-color:grey;
    }
    .son{
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -50px;
        margin-top: -50px;
        width: 100px;
        height: 100px;
        background-color:red; 
    }
</style>

結果:

 

 缺點:需要知道本身這個子盒子的寬度,利用margin-left、margin-top負一半寬度去調整

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM