編碼的世界 / 優質文選 / 生涯

css position:absolute 父元素高度塌陷


2022年7月30日
-   

問題
在使用iSroll v4插件時,無法滾動到底部,從源碼得知最大滾動位置由maxScrollY決定。從源碼摘錄出計算maxScrollY的部分
that.wrapperH = that.wrapper.clientHeight || 1;
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;

當scale為1時,可以簡單的認為
maxScrollY = 父元素.clientHeight - 子元素.offsetHeight

因為父元素.clientHeight=0,所以可滾動區域減小,無法滑動到底部。那麼子元素有高度的情況下,為什麼父元素的clientHeight為0呢?
父元素高度塌陷
我們用demo還原這個問題,審查元素可以發現,子元素有高度,h但父元素高度為0,這不科學呀?! 一番嘗試後,發現是position:absolute搗的鬼,absolute是絕對定位,它會脫離當前文檔流,所以不會撐起父元素。解決辦法就是,設置父元素的最小高度,min-height ,通常會設置為
min-height: calc(100% - 其它元素的高度)

absolute The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.
參考
https://developer.mozilla.org/en-US/docs/Web/CSS/position

熱門文章