首頁  >  文章  >  web前端  >  CSS 垂直水平居中有哪幾種方法

CSS 垂直水平居中有哪幾種方法

php中世界最好的语言
php中世界最好的语言原創
2018-03-20 14:23:051552瀏覽

這次帶給大家CSS 垂直水平居中有哪幾種方法,CSS 垂直水平居中的注意事項有哪些,下面就是實戰案例,一起來看一下。

CSS 居中對齊

  • #程式碼中均省略了瀏覽器前綴

##以下例子以我的個人的標準排序

當然也有更多的居中處理方法但我覺得只有這5種方法是最完善的解決方案

flex 居中

優點:可對未知高度進行居中處理

<style>
    .wrap{height: 100%;display: flex; justify-content: center; align-items: center;align-content:center;}
    
    .other{background-color: #ccc; width: 400px;height: 400px;} /* 额外的样式 可去除 */
</style>
<p class="wrap">
    <p class="other">
        <h2>这是第二层的内容 不会居中</h2>
    </p>
</p>

position + translate 居中

優點:可對未知高度進行居中處理、巢狀層最少

<style>
    /* position 可选 absolute|fixed*/
    .center{position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);}
    
    .other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<p class="center other">
    <h2>这一层的内容 不会居中</h2>
</p>

table-cell 居中

###缺點:1. 居中層需要設定寬度(.center)。 2.外層多嵌套一層(.cell) 3. 居中層必須設定寬度(允許%)###
<style>
    .wrap{display: table;width: 100%;height: 100%;}
    .cell{display: table-cell;vertical-align:middle;}
    .center{width: 400px;margin-left:auto;margin-right:auto;}
    .other{background-color: #ccc;  height: 400px;} /* 额外的样式 可去除 */
</style>
<p class="wrap">
    <p class="cell">
        <p class="center other">
            <h2>这一层的内容 不会居中</h2>
        </p>
    </p>
</p>
###傳統居中(2種)######缺點:1. margin 值必須為auto。 2. 居中層必須設定高寬(允許 %) 3. 必須使用 position###
<style>
    /*
        1. left、top、right、bottom 可以任意,但必须相等
        2. position 可选 absolute|fixed
    */
    .center{position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;margin: auto;width: 400px;height: 400px;}
    .other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<p class="center other">
    <h2>这一层的内容 不会居中</h2>
</p>
###缺點: 居中層必須設定固定高寬,並且magin需要透過高寬計算得出。 ###
<style>
    .wrap{position: relative;height: 100%;}
    .center{position: absolute;left: 50%;top: 50%; width: 400px;height: 300px; margin-left: -200px;margin-top: -150px;}
    .other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<p class="wrap">
    <p class="center other">
        <h2>这一层的内容 不会居中</h2>
    </p>
</p>
###############相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章! ######推薦閱讀:#########重繪與重排如何使用################Canvas來製作旋轉太極的動畫#### #####

以上是CSS 垂直水平居中有哪幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn