必刷前端面试题:css中如何实现元素的水平垂直居中

126 阅读2分钟

在这个系列里我会为大家讲解一些前端面试里有关css的常考题。在面试官问到我们有关css的问题时,很有可能会问到这些问题。


CSS中如何实现元素的水平垂直居中

  1. 使用定位(Position:absolute) +负边距偏移
// html
<div class="A">
    <div class="B"></div>
</div>

// css
.A{
      width: 500px;
      height: 500px;
      background-color: antiquewhite;
      position: relative; //设置元素的定位方式为相对定位,元素不会脱离文档流。
   }
.B{
      width: 200px;
      height: 200px;
      background-color: #5cd552;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%); //相对于元素自身将元素沿着X轴(水平方向)和Y轴(垂直方向)分别移动其自身宽度和高度的50%。
    }

transfrom搭配绝对定位可以实现元素的水平和垂直居中。通过定位将子元素移动到正中央,然后使用负边距偏移自身宽高的一半。

  1. 在已知宽高的情况下使用定位(Position:absolute) + margin负值
// html
<div class="A">
    <div class="B"></div>
</div>

// css
.A{
      width: 500px;
      height: 500px;
      background-color: antiquewhite;
      position: relative; //设置元素的定位方式为相对定位,元素不会脱离文档流。
   }
.B{
      width: 200px;
      height: 200px;
      background-color: #5cd552;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -100px; 
      margin-top: -100px;
    }

通过调整position属性、百分比定位以及负margin值的组合,可以实现元素的精确居中。

  1. 使用弹性布局(display: flex)
// html
<div class="A">
    <div class="B">hello world</div>
</div>

// css
.A{
      width: 500px;
      height: 500px;
      background-color: antiquewhite;
      position: relative; //设置元素的定位方式为相对定位,元素不会脱离文档流。
      display: flex;
      justify-content: center;
      align-items: center;
   }
.B{
      background-color: #5cd552;
    }

采用了Flexbox布局,并且通过justify-content和align-items属性实现了在水平和垂直方向上的居中对齐。

  1. 使用网格布局(display: grid)
// html
<div class="A">
    <div class="B">hello world</div>
</div>

// css
 .A{
      width: 500px;
      height: 500px;
      background-color: antiquewhite;
      display: grid;//设定为网格容器,允许使用网格布局来对其子元素进行排列
      justify-content: center; // 水平居中
      align-items: center; // 垂直居中
    }
    .B{
      background-color: #5cd552;
    }
  1. 使用表格布局(display: table-cell)+vertical-align (子容器不能是块级)
// html
<div class="A">
    <div class="B">hello world</div>
</div>

// css
 .A{
      width: 500px;
      height: 500px;
      background-color: antiquewhite;
      display: table-cell;
      text-align: center; //用来控制非块级元素的水平居中
      vertical-align: middle;//垂直方向上居中对齐。
    }
    .B{
      display: inline-block;
      width: 200px;
      height: 200px;
      background-color: #5cd552;
    }

总结

在css中有多种方式可以实现元素的水平垂直居中,其中Flexbox和Grid不仅可以实现居中,还能提供更复杂的布局方案,是实现元素水平垂直居中的最优解。当然具体的选择还需要根据实际的开发情况来决定。