html中盒子居中方法

方法一:flex布局

            /* 弹性容器*/
            display: flex;
             /* 主轴居中 */
            justify-content: center;
             /* 侧轴居中 */
            align-items: center;

缺点:盒子无法覆盖其他标准流

方法二:用magin和padding将盒子挤到中心 

方法三:margin+定位(子绝父相)


            background-color: pink;
            position: absolute;
            left: 50%;
            top:50%;
            margin-left:-100px;
            margin-top:-50px;
            width:200px;
            height:100px;

缺点:盒子的宽高要固定

方法四:定位+margin实现

            position: absolute;
            left: 0;
            top:0;
            bottom: 0;
            right: 0;
            /* 脱离了标准流,margin自适应可以垂直居中、 */
            margin: auto;
            width: 12.5rem;
            height: 6.25rem;
            background-color: pink;

方法五:位移+居中(推荐)

原理:位移取值为百分比数值,参考盒子自身尺寸计算移动距离

            width:200px;
            height:100px;
            background-color: pink;
            position: absolute;
            left: 50%;
            top:50%;
            /* 位移+定位(子绝父相)推荐写法 */
            transform: translate(-50%,-50%);
  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
有多种方法可以实现HTMLdiv盒子居中,其包括使用弹性盒模型、position属性与margin调整等方法。我们可以根据需要选择合适的方法来实现盒子居中。 例如,可以使用弹性盒模型的justify-content和align-items属性来实现水平和垂直方向的居中。同时,也可以使用position属性和transform属性的translate函数来实现盒子居中。 下面是三种方法的示例代码: 方案一:使用弹性盒模型 ``` <style> body { margin: 0; } .a { display: flex; justify-content: center; /*水平居中*/ align-items: center; /*垂直居中*/ height: 600px; width: 600px; border: 1px solid black; } .box { width: 200px; height: 200px; background-color: pink; } </style> <div class="a"> <div class="box"></div> </div> ``` 方案二:使用position和margin调整 ``` <style> .a { position: relative; width: 600px; height: 600px; border: 1px solid black; } .box { position: absolute; width: 200px; height: 200px; top: 0; left: 0; right: 0; bottom: 0; background-color: pink; margin: auto; } </style> <div class="a"> <div class="box"></div> </div> ``` 方案三:使用position和transform ``` <style> .a { position: relative; width: 600px; height: 600px; border: 1px solid black; } .box { position: absolute; width: 200px; height: 200px; top: 50%; /*盒子左上角的那个点在页面正间*/ left: 50%; background-color: pink; transform: translateX(-50%) translateY(-50%);/*不需要知道盒子宽度*/ } </style> <div class="a"> <div class="box"></div> </div> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值