绝对定位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来撑开父元素。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章