html 盒子在其包含块中居中总结

行盒(行块盒)水平居中

直接设置行盒(行块盒)父元素:text-align:center

常规流块盒水平居中

定宽,设置左右margin为auto(margin:0 auto)

绝对定位元素的水平居中

定宽,设置左右的坐标为0(left:0;right:0;),将左右margin设置为auto

实际上,固定定位(fixed)是绝对定位(absolute)的特殊情况

单行文本垂直居中

设置文本所在元素的行高,为整个区域的高度

行块盒或块盒内多行文本的垂直居中

没有完美方案

设置盒子上下文的内边距(padding)相同,达到类似的效果

绝对定位的垂直居中

定高,设置上下的坐标为0(top:0;bottom:0;),上下margin为auto

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值