HTML/CSS - Best practice for preserving white space on certain elements?

HtmlCssWhitespace

Html Problem Overview


What is the best way to preserve white space in HTML? We have a lot of pages that bring down data from our database, and the data may have multiple spaces in it. The rendered HTML elements that hold the data vary from anchor tags (<a>), spans (<span>), table rows (<tr>, <td>, etc.

The easiest thing to do right now would be to add a global css class like so:

body a, span, tr, td { white-space: pre; }

I'm wondering if there is a better way to implement this without assigning a class to each individual HTML element.

Html Solutions


Solution 1 - Html

I would use the same technique, but inside a data class wrapper where it is needed:

.data a, .data span, .data tr, .data td { white-space: pre; }

HTML:

<div class="data">
....

</div>

Solution 2 - Html

<pre>no need for       style</pre>

Solution 3 - Html

This depends on whether you wish to preserve all whitespace in certain elements and what exactly should happen there. Assuming that there are no CSS rules that might interfere, your CSS can be simplified to

a, span, tr { white-space: pre; }

because an a element is alway within body and td by default inherits the property from tr.

If you only wish to prevent multiple spaces from collapsing, instead of forcing fixed division to lines, then white-space: pre-wrap or replacing spaces by no-break spaces might be more adequate.

Finally, the need and possibilities for restricting the rule to selected elements greatly depend on how the selection should be done. Perhaps you can selectively set white-space to pre (or pre-wrap) to some elements that enclose the relevant parts, remembering that the property inherits if not set on inner elements.

You can also break the inheritance: you could set white-space: pre on a table element for example, if you wish to make the rule apply to most of the content, and set white-space: normal on those rows or cells where it is not to be applied.

Solution 4 - Html

What is wrong with replacing spaces by &nbsp;? This should work inside any element and preserve the spaces in the rendered output.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncontactmattView Question on Stackoverflow
Solution 1 - HtmlDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 2 - HtmlLastTribunalView Answer on Stackoverflow
Solution 3 - HtmlJukka K. KorpelaView Answer on Stackoverflow
Solution 4 - HtmlLars HankeView Answer on Stackoverflow