CSS-div垂直居中方法总结

【第一种】
该方法是通过position定位去实现的,通过将上下左右的偏移值全设为0,再利用margin:auto,让盒子上下,左右宽度相同,将盒子挤到中间。

//html结构
<div class="outer">
      <div class="box"></div>
</div>
//css样式
.outer{
            width: 500px;
            height: 500px;
            background-color: rgb(158, 177, 194);
            position: relative;
        }
        .box {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: skyblue;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }

【第二种】
该方法使用的频率较多,是根据div子盒子自身的大小去偏移。
利用left,top属性距父盒子偏移50%,但是不要忘记子盒子自身是有宽度的,将子盒子往相反方向偏移自身的一半。

//css样式
 .outer{
            width: 500px;
            height: 500px;
            background-color: rgb(158, 177, 194);
            position: relative;
        }
        .box {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: skyblue;
            left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }

【第三种】
该方法是利用css3中的transform属性,和第二种方法原理上是相同的,但是一般面试的时候面试官喜欢问利用css3中的方法来实现盒子的水平居中。

//css代码
.outer{
            width: 500px;
            height: 500px;
            background-color: rgb(158, 177, 194);
            position: relative;
        }
        .box {
            position: absolute;
            width: 200px;
            height: 200px;
            background-color: skyblue;
            left: 50%;
            top: 50%;
           transform: translate(-50%,-50%);
        }

【第四种】
使用flex布局实现

  <style>
        .outer{
            width: 500px;
            height: 500px;
            background-color: rgb(158, 177, 194);
            display: flex;
        }
        .box {
            width: 200px;
            height: 200px;
            background-color: skyblue;
            margin: auto;
        }
    </style>

    
<body>
    <div class="outer">
        <div class="box"></div>
    </div>
</body>
<style>
 .outer{
            height: 100vh;
            background-color: rgb(158, 177, 194);
            display: flex;
            /* 水平居中 */
            justify-content: center;
            /* 垂直居中 */
            align-items: center;
        }
        .box {
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
</style>


<body>
    <div class="outer">
        <div class="box"></div>
    </div>
</body>

以上总结的都是比较常见的方法,希望这篇文章对你有所帮助哦~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值