You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单行文本设置部分字体大小出现意外滚动,求原因与解决方法

Why does a single-line div with font-size:17px get a 1px scrollbar on Linux Chrome/Firefox?

Great question—this is a quirky edge case tied to how Linux-based browsers render fonts and handle pixel rounding. Let’s break down what’s happening, why it occurs, and how to fix it.

What’s causing the 1px difference between scrollHeight and offsetHeight?

The core issue boils down to two related factors:

  • Fractional pixel font rendering: On Linux, browsers use engines like Skia (Chrome) or FreeType (Firefox) that often calculate text height as a fractional value for non-integer font sizes (like 17px). For example, a 17px font might actually render to a line height of ~17.2px due to inherent font metrics (ascenders/descenders that don’t align perfectly with whole pixels).
  • Pixel rounding inconsistencies: offsetHeight represents the element’s visible height rounded to the nearest whole pixel, while scrollHeight measures the exact content height (including fractional overflow rounded up). When the content’s actual height is just barely over a whole pixel (e.g., 17.1px), offsetHeight becomes 17px but scrollHeight gets rounded up to 18px—creating that tiny gap that triggers the scrollbar.

Even with only one line of text, the browser’s font rendering doesn’t perfectly align the text’s height with the div’s computed height, leading to unintended overflow.

Fixes to eliminate the 1px scrollbar

Here are reliable solutions tailored to this issue:

1. Explicitly set line-height to match font-size

By forcing the line height to exactly match your font size, you eliminate extra height from default font metrics:

div {
  font-size: 17px;
  overflow: auto;
  line-height: 17px; /* Exact match to font-size */
}

This ensures the text’s total height fits perfectly within the div’s bounds.

2. Use height: fit-content

Let the div automatically size to fit its content, which accounts for any fractional rendering quirks:

div {
  font-size: 17px;
  overflow: auto;
  height: fit-content;
}

This guarantees the div’s height will always wrap the text without overflow.

3. Switch to a font size that avoids fractional rendering

Some integer font sizes (like 16px or 18px) render more cleanly on Linux browsers, as their metrics align better with whole pixels. Testing with these sizes often eliminates the 1px overflow entirely.

4. Fall back to overflow: hidden (if scroll isn’t needed)

If you don’t require scroll functionality for the div, simply hide any overflow:

div {
  font-size: 17px;
  overflow: hidden;
}

内容的提问来源于stack exchange,提问作者mixture

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:49:49