【让盒子垂直水平居中】


我们在用css布局嵌套盒子时,肯定遇到过让盒子垂直水平居中的问题,今天我就简单总结几个常见的垂直水平居中的方式,大家还有什么比较好的方式也可以留言哦。

首先,创建两个盒子,box盒子在div盒子面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background: #55a532;
            margin: 0 auto;
        }
        .box{
            width: 10px;
            height: 10px;
            background: #3fefef;
            margin: 0 auto;
           
        }

    </style>
</head>
<body>
   <div>
    <div class="box"></div>
   </div>
</body>
</html>

盒子样式如图
在这里插入图片描述

方式一

利用文本居中和行高来实现

先用display:inline-block将子盒子转换为行内块,然后用文本水平居中和行高让box盒子水平垂直居中。由于对齐方式的不同,给box盒子添加vertical-align: middle;

 div{
            width: 100px;
            height: 100px;
            background: #55a532;
            margin: 0 auto;
            text-align: center;
            line-height: 100px;
        }
        .box{
            width: 10px;
            height: 10px;
            background: #3fefef;
            display: inline-block;
            vertical-align: middle;


        }

方式二

利用绝对定位和外边距来实现

先为父盒子设置相对定位,再为子盒子设置绝对定位,且绝对定位的四个方向的值都为0,然后将外边距margin设为auto。

 div{
            width: 100px;
            height: 100px;
            background: #55a532;
            margin: 0 auto;
            position: relative;
        }
        .box{
            width: 10px;
            height: 10px;
            background: #3fefef;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            此外,还可以在设置绝对定位的前提下,用位移transform: translate来实现居中

方式三

先在父元素中添加display:flex;,然后在父元素中添加主轴居中(justify-content:center)和侧轴居中(align-item:center)即可

 div{
            width: 100px;
            height: 100px;
            background: #55a532;
            margin: 0 auto;
            dispaly:flex;
            justify-content:center;
            align-item:center
        }
        .box{
            width: 10px;
            height: 10px;
            background: #3fefef;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值