1. 河豚號 > 生活百科 >

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

 

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

絕對定位

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

css篇——前端面試中常問(wèn)的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>

彈性方法居中

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

  <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進(jìn)行比偏移。

  <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種是常用的方法,當然還有其他居中方法比如grid布局,table-cell布局等。

 
 
 

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

聯(lián)系我們

在線(xiàn)咨詢(xún):點(diǎn)擊這里給我發(fā)消息

微信號:15705946153

工作日:9:30-18:30,節假日休息

国产精品亚洲w码日韩中文|国产高清露脸孕妇系列|久久国语露脸国产精品|久久久777精品电影网影网|欧美高大丰满freesex