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

來源:互聯網
上載者:User
這次給大家帶來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製作旋轉太極的動畫

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.