I'm currently exploring ways to incorporate line numbers into text within a <pre>
tag, all while maintaining the ability for the text to wrap. This presents some unique challenges:
- Adding line numbers in a separate column of a table is not an option, as word wrapping would disrupt their alignment.
- Line numbers should not be part of the actual text content (they should not be selected or copied along with the text, and wrapped lines should align to the right of the line numbers).
As a solution, I have devised a method involving two <span>
elements: one for the line number and another for the text on that line [0]. To prevent the text in the second <span>
from wrapping below the first <span>
, it is styled as an inline-block
:
span {
display: inline-block;
white-space: pre-wrap;
}
<pre><span>12345 </span><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</pre>
However, a setback of this approach is that the second <span>
allows the text to wrap beyond the boundaries of the parent <pre>
. It appears that the <span>
wraps the text based on the width of the <pre>
, regardless of its offset due to the first <span>
.
Here is a simple example illustrating this issue: http://jsfiddle.net/fgdhyde6/1/
My queries are:
What is the reason behind this behavior? This behavior is consistent in both Safari 9.0.1 and Firefox 42.0, indicating it may not be a browser-specific bug.
If this behavior is intentional, how can I address it with a more generalized solution (without manually setting the width of the first
<span>
)?
Update
This issue does not seem to be confined to <pre>
tags and specific white-space
settings like pre-wrap
, as initially presumed. It is also observed with two <span>
elements within a <div>
: http://jsfiddle.net/fgdhyde6/2/
[0]: Ultimately, the line numbers will be introduced using an appropriate
:before { content: counter(...); }
, preventing them from being included when copying text. Nonetheless, the issue with text overflowing persists regardless of the technique used.