让盒子水平垂直居中常见的四种方法(4种)

一到三种方法都会配合定位来使用, 所以当子盒子添加了绝对定位; 那么父盒子一定要加上相对定位(简称父绝子相).

第一种:

        使用定位配合margin的负值使用, 注意这里的margin负值是对于子盒子自身的宽高而言的.

<style>
        .father {
            position: relative;
            width: 400px;
            height: 400px;
            margin: 100px auto;
            background-color: pink;

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

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

     

 第二种:

        使用定位和transform位移一起使用, 注意transform位移的百分比值也是子盒子自身的宽高的一半.

<style>
        .father {
            position: relative;
            width: 400px;
            height: 400px;
            margin: 100px auto;
            background-color: pink;
        }
        
        .son {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 200px;
            height: 200px;
            background-color: red;
            transform: translate(-50%, -50%);
            /* 位移的百分比相对于盒子的自身宽高而言 */
        }
</style>


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

第三种:

        将top, left, right和bottom值全部设置为0, 然后使用margin: auto;

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


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

第四种:

         给父元素设置flex布局, 然后设置主轴和侧轴实现子盒子在父元素中垂直水平居中

  <style>
    .father {
      display: flex;
      width: 400px;
      height: 400px;
      justify-content: center; // 在主轴上居中
      align-items: center; // 在侧轴上居中
      margin: 100px auto;
      background-color: pink;
    }

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

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

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值