绝对定位position:absolute下,父元素高度塌陷/无法撑开父盒子的原因和解决方案

我一直很困惑绝对定位后父盒子的高度会变为0,如何让绝对定位的元素撑开父盒子呢?

我在StackOverflow上找到的高分解决方案如下:

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

翻译:
绝对定位的元素完全从文档流当中移走,所以他们的尺寸无法影响到父元素的尺寸。
如果你真的想实现绝对定位还能撑开父元素,只能通过JavaScript实现:获取到绝对定位的子元素的高度,再设置给父元素。
或者,用 float: left / float:right 还有 margin 来调整位置,子元素再通过父元素设置的overflow:hidden来撑开父元素。

  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值