css position:absolute 父元素高度塌陷

本文探讨了使用iScroll v4插件时遇到的无法滚动到底部的问题,分析了maxScrollY的计算原理,指出在特定CSS定位下父元素高度塌陷的原因,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值