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

盒子居中对齐的常见方式

首先 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%);
  }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值