垂直居中的多種方式「html中div水平居中」

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

絕對定位

  • 父級元素(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彈性布局設置垂直居中和水平居中

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

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/252404.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-14 02:16
下一篇 2024-12-14 02:16

相關推薦

發表回復

登錄後才能評論