首頁  >  文章  >  web前端  >  設定元素水平、垂直居中有哪兩種方式

設定元素水平、垂直居中有哪兩種方式

一个新手
一个新手原創
2017-10-20 09:14:171181瀏覽

  做一個水平和垂直居中的模態彈框這麼一個小需求,對於我們這些前端來說,應該是常事。

  在css3出來以前,我們要想讓元素既水平居中又要垂直居中只有一個辦法(我能想到的),就是透過js計算,把它們定位到螢幕中間位置。這方法比較笨,也很麻煩。

  以下兩種方式,可以讓元素快速定位到螢幕中間。

  flex佈局


#
<style>
    .flex-mask {
        display: flex;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        align-items: center;  // 垂直居中
        justify-content: center;  // 水平居中
        background: rgba(0,0,0,.5);
    }
    .flex-box {
        width: 500px;
        height: 300px;
        background-color: #fff;
        border-radius: 10px;
    }
</style>

<!-- 元素 -->
<p class="flex-mask">
    <p class="flex-box"></p>
</p>

   #使用translate


#
c9ccee2e6ea535a969eb3f532ad9fe89
    .transform-box {
        position: fixed;
        z-index: 2;
        top: 50%;
        left: 50%;
        width: 300px;
        height: 150px;
        background-color: red;
        border-radius: 10px;
        transform: translate(-50%, -50%);
    }
531ac245ce3e4fe3d50054a55f265927
1496b9ead66877b9376ec97ce364601494b3e26ee717c64999d7867364b1b4a3

以上是設定元素水平、垂直居中有哪兩種方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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