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

发布了336 篇原创文章 · 获赞 369 · 访问量 193万+

猜你喜欢

转载自blog.csdn.net/wangjun5159/article/details/102527004