元素水平垂直居中的四种常见方式

1.子绝父相定位 + margin: auto

2.子绝父相定位 + margin移动子元素自身高宽一半的值

3.子绝父相定位 + transform

4.flex弹性布局

目录

1.子绝父相定位 + margin: auto

2.子绝父相定位 + margin移动子元素自身高宽一半的值

3.子绝父相定位 + margin移动自身高宽的50%

4.flex弹性布局


1.子绝父相定位 + margin: auto

父盒子设置相对定位,子盒子设置绝对定位,子盒子的上下左右定位值都为0,此时如果子盒子没有宽高,将会撑满整个父盒子,设置宽高之后给一个margin:auto属性,就能实现水平垂直居中

  <style>
    .father {
      width: 300px;
      height: 300px;
      position: relative;
      background-color: pink;
    }

    .son {
      width: 100px;
      height: 100px;
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      background-color: skyblue;
    }
  </style>
</head>

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

</body>

2.子绝父相定位 + margin移动子元素自身高宽一半的值

父盒子设置相对定位,子盒子设置绝对定位,然后将子盒子定位到父盒子top:50% left:50%的位置,此时子盒子并不在父盒子中心,而是偏右下,只需要将子盒子向上向右移动自身一半的值就可以实现水平垂直居中(注意:需要知道子盒子的宽高,父盒子宽高发生变化也不影响)

<style>
    .father {
      width: 500px;
      height: 500px;
      position: relative;
      background-color: pink;
    }

    .son {
      width: 100px;
      height: 100px;
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -50px;
      margin-top: -50px;
      background-color: skyblue;
    }
  </style>
</head>

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

 3.子绝父相定位 + transform

这个方法可以说是第二种方法的升级版,父盒子设置相对定位,子盒子设置绝对定位,然后将子盒子定位到父盒子top:50% left:50%的位置,此时子盒子并不在父盒子中心,而是偏右下,只需要使用transform属性向上向下移动子盒子自身高宽的50%,就可以实现水平垂直居中(需要知道子盒子的宽高)

 <style>
    .father {
      width: 300px;
      height: 300px;
      position: relative;
      background-color: pink;
    }

    .son {
      width: 100px;
      height: 100px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      background-color: skyblue;
    }
  </style>
</head>

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

4.flex弹性布局

使用flex布局可以非常方便的实现水平垂直居中,实现flex弹性布局要给子元素的父元素设置displa:flex,通过justify-content: center和align-items: center实现水平垂直居中

 <style>
    .father {
      width: 300px;
      height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: pink;
    }

    .son {
      width: 100px;
      height: 100px;
      background-color: skyblue;
    }
  </style>
</head>

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

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值