(2019)[前端]面試題[6]:水平垂直居中方法

  • 2019 年 11 月 13 日
  • 筆記

問題

水平垂直居中的實現方式,儘可能多

Hello,歡迎來到我的博客,每天一道面試題,我們共同進步。

解答

這個有很多方法,我們一個個來說。

方法一:absoulte + transform(此方法未知子元素寬度)

<div class="parent">      <div class="child">        </div>  </div>
.parent {      background-color: #eee;      width: 500px;      height: 500px;      margin: 10px auto;      position: relative;  }    .child {      width: 200px;      height: 200px;      background-color: lightcoral;      position: absolute;      top: 50%;      left: 50%;      transform: translate(-50%, -50%);  }

說明:父元素相對定位,子元素絕對定位。 並且子元素top,left各50% 然後transform: translate(-50%, -50%); 此方法未知子元素寬高度(也就是說可以隨便變換寬高度)

如果已知子元素寬高度,那麼transform: translate(width/2,height/2);一樣的效果。

(而這裡就不能隨便變換寬高度,變了就要改變translate的值)

方法二:flex布局

這是非常簡單的一種方法

<div class="parent">      <div class="child">        </div>  </div>
.parent {      background-color: #eee;      display: flex;      justify-content: center;      align-items: center;      width: 500px;      height: 500px;      margin: 10px auto;  }    .child {      width: 200px;      height: 200px;      background-color: lightgreen;  }

將父元素設置為display: flex; justify-content: center; align-items: center; 都設置為居中對齊(分別為主軸居中,交叉軸居中) 涉及到flex語法,可以看flex相關文檔/教程。

方法三:table-cell

<div class="parent">      <div class="child">        </div>  </div>
.parent {      background-color: #eee;      display: table-cell;      text-align: center;      vertical-align: middle;      width: 500px;      height: 500px;      margin: 10px auto;  }    .child {      display: inline-block;      width: 200px;      height: 200px;      background-color: lightslategray;  }

簡介: 父元素display:table-cell; 水平:text-align:center; 居中 垂直:vaertical-align: middle;居中 這還沒完,需要子元素display:inline-block; ,不然只會垂直居中