首頁  >  文章  >  web前端  >  5種CSS垂直水平居中的最佳方案

5種CSS垂直水平居中的最佳方案

小云云
小云云原創
2018-01-13 10:02:461508瀏覽

本文主要跟大家分享CSS 垂直水平居中的5種最佳解決方案以及各自的優缺點,介紹的非常詳細,具有參考借鑒價值,需要的朋友參考下吧,希望能幫助到大家。

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>

相關推薦:

寫模態框時怎麼讓內容垂直水平居中?

關於用css實作文字和圖片垂直水平居中

#使用CSS完美實現垂直水平居中的6種方法介紹

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

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