絕對定位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來撐開父元素。

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