Chrome与Firefox列布局下div的scrollHeight计算差异及适配需求
解决Chrome与Firefox中scrollHeight计算差异的问题
问题现象
在包含多列布局的页面中,.height-wrapper元素的scrollHeight属性在Chrome中返回36px,而在Firefox中返回18px,需要让Firefox采用Chrome的计算逻辑,返回内容的总高度。
问题代码
<html> <head> <style> .column-wrapper{ column-count: 6; column-rule: 0; column-gap: 0; } .fixed-height-container{ height: 2000px; } .height-wrapper { height: 200px; } </style> </head> <body> <div class="fixed-height-container"> <div class="column-wrapper"> <div class="height-wrapper"> <div class="content"> Text </div> <div class="content"> More text </div> </div> </div> </div> <script> const heightWrapper = document.querySelector(".height-wrapper") console.log(heightWrapper.scrollHeight) </script> </body> </html>
解决方案
给.height-wrapper添加break-inside: avoid样式,强制禁止元素在多列布局中被拆分,这样Firefox会按照内容的总高度计算scrollHeight,与Chrome保持一致:
.height-wrapper { height: 200px; break-inside: avoid; }
也可以使用display: inline-block让元素脱离多列布局的流式拆分,同样能达到效果:
.height-wrapper { height: 200px; display: inline-block; width: 100%; }
原因说明
多列布局下,Firefox默认允许子元素内容在列之间拆分,此时scrollHeight计算的是元素在当前列中的高度;而Chrome会直接计算元素所有内容的总高度,忽略列拆分的影响。通过添加禁止拆分的样式或修改元素的显示类型,就能让Firefox的计算逻辑与Chrome对齐。
内容的提问来源于stack exchange,提问作者Talbi Youssef
相关产品推荐
相关产品推荐

