盒子在其包含快中居中

一、水平居中

1.行盒或者行块盒居中

设置父元素快盒 为text-align:center 里面的行盒或者行块盒就会水平居中。

2.块盒水平居中

快盒定宽,左右margin设置为auto就可以。

3.浮动元素水平居中(目前只能通过margin-left调整。其他暂时没有什么好方法)

4.绝对定位水平居中

定宽 left:0 right:0  左右margin为auto  

5.固定定位水平居中和绝对定位的用法一样,只是他们的包含快不一样。

二、垂直居中

1.单行文本垂直居中(line-height:height)

2.多行文本垂直居中(如果文本不在套一层盒子,是没办法做到的,所以想解决多行文本垂直居中可以在文本外侧再套一层盒子,利用绝对定位等方法去实现)

3.绝对定位垂直居中

定高,设置bottom:0 top:0 上下margin为auto

4.固定定位的垂直居中

和绝对定位垂直居中一样

5.行盒或者快盒垂直居中

只能用绝对定位,然后定高 间接垂直居中。或者结合tranlate 也可以用弹性盒模型(此方法最简单) 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
有多种方法可以实现HTML中div盒子居中,其中包括使用弹性盒模型、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、付费专栏及课程。

余额充值