盒子上下、左右居中对齐的常见方式

1,142 阅读1分钟

盒子居中对齐的常见方式

首先 html 布局,两层盒子,实现子盒子相当于父盒子上下、左右分别对齐。

  <div class="div1">
      <div class="div2"></div>
  </div>

然后编写 CSS 实现的具体几种方法如下:

1 第一种:使用CSS的 position 属性和 margin: auto;

  .div1 {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      position: relative;
  }

  .div2 {
      width: 50px;
      height: 50px;
      background-color: red;
      position: absolute;
      margin: auto;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
  }

2 第二种:利用css3的新增属性 display: table-cell; vertical-align:middle;

  .div1 {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      display: table-cell;
      vertical-align: middle;
  }

  .div2 {
      width: 50px;
      height: 50px;
      background-color: red;
      margin: auto;
  }

3 第三种:利用flexbox布局

  .div1 {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      display: flex;
      justify-content: center;
      align-items: center;
  }

  .div2 {
      height: 50px;
      width: 50px;
      background-color: red;
  }

4 第四种:利用 position 和 margin-left 的属性

margin-left 的值取 负自身的一半,此方法需要知道自身宽度,而且后期做调整比较麻烦

  .div1 {
      width: 100px;
      height: 100px;
      border: 1px solid  red;
      position: relative;
  }

  .div2 {
      height: 50px;
      width: 50px;
      background-color: red;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -25px;
      margin-left: -25px;
  }

5 第五种:利用 position 和 transform 的属性

此方法需要考虑兼容问题

  .div1 {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      position: relative;
  }

  .div2 {
      height: 50px;
      width: 50px;
      background-color: red;
      position: absolute;
      top: 50%;
      left: 50%;
      -ms-transform: translate(-50%, -50%);
      -moz-transform: translate(-50%, -50%);
      -o-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
  }