1. 河豚號 > 生活百科 >

html中div水平居中(垂直居中的多種方式)

 

馬上又要到秋招的時候了,又有不少人打算換工作了。前端在面試中總會被問到的一道基礎(chǔ)題div居中方法,這里給大家總結(jié)一下都有哪些常用的方法。

絕對定位

  • 父級元素(parent)采用相對定位(relative),需要居中的元素(demo)采用絕對定位(absolute)。
  • 居中元素向上偏移50%,向左偏移50%,此時左頂點位于中心,不過我們需要的是整體居中,所以在偏移自身一半的寬高。(如下圖)

css篇——前端面試中常問的div居中方法

還未偏移一半自身寬高

<style>
    .parent {
      position: relative;
      width: 500px;
      height: 500px;
      border: solid red 1px;
    }
    .demo {
      position: absolute;
      width: 100px;
      height: 100px;
      border: solid blue 1px;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -50px;
    }
  </style>
  <body>
    <div class="parent">
      <div class="demo"></div>
    </div>
  </body>

彈性方法居中

通過flex彈性布局設(shè)置垂直居中和水平居中

  <style>
    .parent {
      width: 500px;
      height: 500px;
      border: solid red 1px;
      display: flex;
      // 垂直,水平居中
      align-items: center;
      justify-content: center;
    }
    .demo {
      width: 100px;
      height: 100px;
      border: solid blue 1px;
    }
  </style>
  <body>
    <div class="parent">
      <div class="demo"></div>
    </div>
  </body>

使用transform居中

在子元素不知道自身寬高情況,使用transform進行比偏移。

  <style>
    .parent {
      position: relative;
      width: 500px;
      height: 500px;
      border: solid red 1px;
    }
    .demo {
      position: absolute;
      border: solid blue 1px;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  </style>
  <body>
    <div class="parent">
      <div class="demo">居中</div>
    </div>
  </body>

以上3種是常用的方法,當(dāng)然還有其他居中方法比如grid布局,table-cell布局等。

 
 
 

本文由網(wǎng)上采集發(fā)布,不代表我們立場,轉(zhuǎn)載聯(lián)系作者并注明出處:http://www.zmlzfb.cn/shbk/39095.html

聯(lián)系我們

在線咨詢:點擊這里給我發(fā)消息

微信號:15705946153

工作日:9:30-18:30,節(jié)假日休息