css position:absolute 父元素高度塌陷

問題

在使用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

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