css 垂直居中

1、針對(duì)單行文本,可使用line-height=height實(shí)現(xiàn)垂直居中,添加text-align:center可以實(shí)現(xiàn)水平居中。
缺點(diǎn):只使用于單行文本。
2、無高度限制時(shí)可以設(shè)定padding-top=padding-bottom實(shí)現(xiàn)居中。
3、固定高度定位和無固定高度定位都可以通過設(shè)定top left 或者bottom right等將元素距離父組件左上或右下50%的距離,此時(shí)與垂直水平居中相比多移動(dòng)了半個(gè)子元素的寬和高,通過margin-top=-50%子元素height(垂直居中),margin-left=-50%子元素寬度width;或者通過transform:translate(-50%,-50%)向上 向左移動(dòng)子元素寬高的50%。
優(yōu)點(diǎn):代碼量少,瀏覽器兼容性高,支持ie6 ie7.
缺點(diǎn):不支持響應(yīng)式
4、dispaly:table、table-cell,vertical-align:middle利用表格屬性,使單元格內(nèi)容中間與所在行中間對(duì)齊。display:table-cell讓標(biāo)簽元素以單元格形式呈現(xiàn),列斯td標(biāo)簽。
優(yōu)點(diǎn):支持任意內(nèi)容的可變高度,支持響應(yīng)式布局。
缺點(diǎn):ie8以上版本
5、利用display:flex彈性盒子布局,參考css flex布局即可。
示例

image.png

<style>
    .v-middle {
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: blue;
      border: 1px solid yellow;
      width: auto;
    }

    .v-middle1 {
      margin-top: 20px;
      padding-top: 30px;
      padding-bottom: 30px;
      background-color: blue;
      border: 1px solid yellow;
      text-align: center;
      line-height: 60px;
      /* height: 60px; 調(diào)整高度用line-height ,height: 無法垂直居中; */
    }

    .v-middle2 {
      height: 100px;
      width: 100px;
      position: absolute;
      top: 50%;
      background-color: red;
      left: 50%;
      margin-top: -50px;
      margin-left: -50px;
      /* transform: translate(-50%, -50%);無論寬高是否固定,都可以用此屬性設(shè)定居中,寬 高固定是相當(dāng)于margin-top: -50px;margin-left: -50px; */
    }
</style>
<body style="display: inline-flex;">
  <div id="demo" style="height:500px;width:500px;border:1px solid red;position: relative;">
    <div class="v-middle">你好,單行文本居中,line-height=height</div>
    <div class="v-middle1">你好1,單行文本居中,padding-top=padding-bottom</div>
    <div class="v-middle2">你好2,div塊居中,position=absolute</div>
  </div>
  <div style="height: 300px;width: 300px;border: 1px solid red ;display: table;margin-left: 10px;text-align: center;">
    <div style="display: table-cell;vertical-align: middle;border:1px solid yellow">
      <div>表格居中table table-cell</div>
    </div>
    <div style="display: table-cell;vertical-align: middle;border:1px solid blue">
      <div>表格居中table table-cell</div>
    </div>
  </div>
</body>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容