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

前端 未结 4 1550
予麋鹿
予麋鹿 2020-11-27 04:51

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.

4条回答
  •  不知归路
    2020-11-27 05:24

    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.

提交回复
热议问题