【前端面试--CSS】=> 不知道宽高的情况下,如何水平垂直居中?

273 阅读1分钟

面试官:不知道宽高的情况下,如何水平垂直居中。

公司:腾讯、字节


display:table-cell

组合使用display:table-cell和vertical-align、text-align,使父元素内的所有行内元素水平垂直居中 (内部div设置display:inline-block即可)。

这在子元素不确定宽高和数量时,特别实用!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Demo001_displayTable</title>
    <style>
        /*** table-cell middle center组合使用 ***/
        .cell {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            width: 240px;
            height: 180px;
            border:1px solid #666;
        }
    </style>
</head>
<body>
    <div class="cell">
        <p>我爱你</p>
    </div>
    <div class="cell">
        <p>我爱你</p><p>亲爱的中国</p>
    </div>
    <div class="cell">
        <p>我爱你</p><p>亲爱的中国</p><div style="width:100px;height:50px;border:1px solid #ccc;display:inline-block">div(inline-block)</div>
    </div>
</body>
</html>

效果:

image-20210524014539783

transform:translate(-50%,-50%)
translate()函数是css3的新特性,在不知道自身宽高的情况下,可以利用它来进行水平垂直居中。

使用定时,当:top:50%, left:50%,是以左上角为原点,故不处于中心位置。

translate(-50%, -50%)作用是,往上(X轴),左(Y轴)移动自身长度的50%,以使其居于中心位置。

与负margin-left和margin-top实现居中不同的是,margin-left必须知道自身的宽高,而translate可以在不知道宽高的情况下进行居中,

tranlate()函数中的百分比是相对于自身宽高的百分比,所以能进行居中
.content {   
   padding:10px;
    background:green;
    color:#fff;
    position:absolute;
    top:50%;
    left:50%;
    border-radius: 5px;
    
    -webkit-transform: translate(-50%,-50%);/*兼容处理*/
    -moz-transform: translate(-50%,-50%);
    
    transform:translate(-50%,-50%);
}
弹性布局flex
display:flex; 设置.wrap为弹性布局

justify-content:center;定义项目在主轴(水平方向)上居中对齐

align-items:center;定义项目在交叉轴(垂直方向)上居中对齐
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
  *{
      margin: 0;
      padding: 0;
  }
  .wrap{
      width: 100px;
      height: 100px;
      border: 1px solid #000;
      margin: 3.125em auto;
      display: flex;
      justify-content: center;
      align-items: center;

  }
  .in{
      width: 10px;
      height: 10px;
      background: #000;
      border-radius: 50%;
  }
  </style>
</head>
<body>
  <div class="wrap">
      <div class="in"></div>
  </div>
</body>
</html>

效果:

image-20210524014622747