October 27, 2024
Chicago 12, Melborne City, USA
HTML

Why does the white space preceding a element containing visually collapse only when text wraps?


JSFiddle demonstration

Say I have something like this in a container small enough that forces it to wrap:

<p>Nihongo | <ruby>日<rt>に</rt>本<rt>ほん</rt>語<rt>ご</rt></ruby></p>

The white space preceding the <ruby> element appears fine if everything is on one line, but if the text wraps (eg. container is too small), that preceding white space is collapsed visually (if I copy and paste the text elsewhere it shows up fine).

Nihongo |日
本語


If I remove that space so that it looks like this:

<p>Nihongo |<ruby>日<rt>に</rt>本<rt>ほん</rt>語<rt>ご</rt></ruby></p>

The second Japanese character moves up if there’s enough room, so it’s as though the space in the above example does take up space (causing the second Japanese character to wrap), just not visually.

Nihongo |日本


If I have a <ruby> without <rt> element in it (pointless, I know), this problem doesn’t occur:

<p>Nihongo | <ruby>日本語</ruby></p>

Nihongo | 日
本語


Initially, I expected this to be a problem with non-alphanumerical text, but while playing around in JSFiddle I found out the culprit was <rt> itself. The same behaviour occurs even if I do the following:

<ruby>日<rt>ni</rt>本<rt>hon</rt>語<rt>go</rt></ruby>

<ruby>日<rt></rt>本語</ruby>

<ruby style="word-break:break-all">ni<rt>ni</rt>hon<rt>hon</rt>go<rt>go</rt></ruby>

yes, even the empty <rt>!


I’ve managed to get around the problem using <span> as pseudo-<rt>s and <rb>s, which is included in the JSFiddle, but I’m more looking for an explanation than a solution. I’d also prefer using just <rt> if possible because the pseudo one is just hard to read, especially since I need to keep a closing and the next opening <ruby> tag together without a space or line break like this: </ruby><ruby> (otherwise a white space is automatically added, resulting in 日 本 語 instead).

(not quite relevant but I also tried using Javascript to reduce font-size if its width is longer than the container, though it was a little expensive for my tastes.)

I tried reading W3C documentations on <ruby> but only see clarifications on how white-space works inside the <ruby> structure, not outside (and the documentations are a little over my head).

Simplified images:

This is what I get

What I expected



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video