子盒子水平垂直居中的几种方式

子盒子水平垂直居中的几种方式。

所有的结构都是,父盒子套一个子盒子。

 <div class="father">
    <div class="son"></div>
  </div>

第一种(定位)

不推荐使用,有点麻烦。

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: lightgreen;
    position: relative;
  }
  .son {
    width: 200px;
    height: 200px;
    background-color: purple;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
  }
</style>

第二种(定位)

四个0,再加 margin: auto

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: lightgreen;
    position: relative;
  }
  .son {
    width: 200px;
    height: 200px;
    background-color: purple;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
  }
</style>

第三种(定位)

利用translate 实现盒子在x轴和y轴各移动-50%,来实现子盒子水平垂直居中

<style>
  .father {
    width: 400px;
    height: 400px;
    background-color: lightgreen;
    position: relative;
  }
  .son {
    width: 200px;
    height: 200px;
    background-color: purple;

    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>

第四种(Flex布局)

Flex 布局(弹性布局) 全称:Flexible Box

注意,设为 Flex 布局以后,子元素的 float、clear 和 vertical-align 属性将失效

推荐使用,这种实现子盒子水平垂直居中,非常简便,只需要给父盒子三行代码即可实现,但需要考虑兼容性。

 <style>
    .father {
      width: 400px;
      height: 400px;
      background-color: pink;
 
      display: flex;
      /*`沿主轴居中排列 */
      justify-content: center;
      /*沿侧轴居中排列*/
      align-items: center;
    }
    .son {
      width: 200px;
      height: 200px;
      background-color: purple;
    }
  </style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值