css樣式水平居中和垂直居中的方法


水平居中(包含塊中居中)

1. 定寬,左右margin為auto。(常規流塊盒、彈性項目[不用定寬])

例子:在box1盒子上設置寬,再設置margin:auto;

<style>
    .box1 {
        width: 200px;
        height: 200px;
        background-color: black;
        margin: auto;
    }
</style>

<body>
    <div class="box-all">
        <div class="box1"></div>
    </div>
</body>

得到的效果:

 

 

 

2. 彈性盒設置justify-content: center,讓彈性項目在主軸上居中。(普遍適應)

例子:在其父元素上設置彈性盒子,和對齊方式;

<style>
    .box-all {
        display: flex;
        justify-content: center;
    }
    
    .box1 {
        width: 200px;
        height: 200px;
        background-color: black;
    }
</style>

<body>
    <div class="box-all">
        <div class="box1"></div>
    </div>
</body>

得到的效果:

3. 父元素設置text-align: center,讓其內部的行盒、塊盒居中(文本)。

例子:在盒子上設置text-align:center;文本自動居中;

<style>
    p {
        text-align: center;
    }
</style>

<body>
    <div class="box-all">
        <p>這是一段文本。</p>
    </div>
</body>

得到的效果:

 

 

 

4. 相對定位元素,margin-left:50%; transform:translateX( -50%)。[margin,padding相對於包含塊寬度的百分比] 【終極方案】

例子:對盒子設置相對定位屬性,在用上面方式進行定位;

<style>
    .box1 {
        width: 200px;
        height: 200px;
        background-color: black;
        position: relative;
        margin-left: 50%;
        transform: translateX(-50%);
    }
</style>

<body>
    <div class="box-all">
        <div class="box1"></div>
    </div>
</body>

得到的效果:


垂直居中(方法與上面類似,我就不演示了)

1. 單行文本垂直居中,設置父元素的line-height為包含塊高度。

2. 彈性盒設置align-items:center,讓彈性項目在側軸上居中。

3. 相對定位元素,top:50%;transform:translateY(-50%)。【終極方案】

 


免責聲明!

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



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