溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

css垂直居中元素的方法

發(fā)布時間:2020-07-02 11:56:47 來源:億速云 閱讀:162 作者:Leah 欄目:web開發(fā)

這篇文章運用簡單易懂的例子給大家介紹css垂直居中元素的方法,代碼非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

垂直居中

1.單行內(nèi)聯(lián)元素垂直居中

<div id="box">
     <span>單行內(nèi)聯(lián)元素垂直居中。</span>。
</div>
<style>
 #box {
    height: 120px;
    line-height: 120px;
    border: 2px dashed #f69c55;
    }
</style>

2.多行內(nèi)聯(lián)元素垂直居中

①利用flex布局(flex)

利用flex布局實現(xiàn)垂直居中,其中flex-direction: column定義主軸方向為縱向。這種方式在較老的瀏覽器存在兼容性問題。

<div class="parent">
    <p>Dance like nobody is watching, code like everybody is.    
    Dance like nobody is watching, code like everybody is.    
    Dance like nobody is watching, code like everybody is.</p>
</div>
<style>
    .parent { 
        height: 140px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border: 2px dashed #f69c55;
    }
</style>

css垂直居中元素的方法

②利用表布局(table)

利用表布局的vertical-align: middle可以實現(xiàn)子元素的垂直居中

<div class="parent">
    <p class="child">The more technology you learn, the more you realize how little you know.
    The more technology you learn, the more you realize how little you know.
    The more technology you learn, the more you realize how little you know.</p>
</div>
 <style>
    .parent {
        display: table;
        height: 140px;
        border: 2px dashed #f69c55;
    }
    .child {
        display: table-cell;
        vertical-align: middle;
    }
</style>

3 塊級元素垂直居中

①使用absolute+負(fù)margin(已知高度寬度)

通過絕對定位元素距離頂部50%,并設(shè)置margin-top向上偏移元素高度的一半,就可以實現(xiàn)了。

<div class="parent">
    <div class="child">固定高度的塊級元素垂直居中。</div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px;
}

②使用absolute+transform

當(dāng)垂直居中的元素的高度和寬度未知時,可以借助CSS3中的transform屬性向Y軸反向偏移50%的方法實現(xiàn)垂直居中。但是部分瀏覽器存在兼容性的問題。

<div class="parent">
    <div class="child">未知高度的塊級元素垂直居中。</div>
</div>
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}

③使用flex+align-items

通過設(shè)置flex布局中的屬性align-items,使子元素垂直居中。

<div class="parent">
    <div class="child">未知高度的塊級元素垂直居中。</div>
</div>
.parent {
    display:flex;
    align-items:center;
}

④使用table-cell+vertical-align

通過將父元素轉(zhuǎn)化為一個表格單元格顯示(類似 <td> 和 <th>),再通過設(shè)置 vertical-align屬性,使表格單元格內(nèi)容垂直居中。

<div class="parent">
  <div class="child">Demo</div>
</div>
<style>
  .parent {
    display: table-cell;
    vertical-align: middle;
  }
</style>

關(guān)于css垂直居中元素的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI