HTML/CSS - 在某些元素上保留空白的最佳实践?
在 HTML 中保留空白的最佳方法是什么?我们有很多页面从数据库中获取数据,并且数据中可能有多个空格。保存数据的呈现的 HTML 元素不同于锚标记 ()、跨度 ()、表格行(、 等)
。现在最简单的事情就是添加一个全局 css 类,如下所示:
body a, span, tr, td { white-space: pre; }
我想知道是否有更好的方法来实现此而不为每个单独的 HTML 元素分配一个类。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用相同的技术,但在需要它的数据类包装器中:
HTML:
I would use the same technique, but inside a data class wrapper where it is needed:
HTML:
这取决于您是否希望保留某些元素中的所有空白以及那里到底应该发生什么。假设没有可能干扰的 CSS 规则,您的 CSS 可以简化为,
因为默认情况下
a
元素始终位于body
和td
内从tr
继承该属性。如果您只想防止多个空格折叠,而不是强制对行进行固定分割,那么
white-space: pre-wrap
或用不间断空格替换空格可能更合适。最后,将规则限制为选定元素的必要性和可能性很大程度上取决于如何进行选择。也许您可以有选择地将
white-space
设置为pre
(或pre-wrap
)到包含相关部分的某些元素,请记住该属性如果未在内部元素上设置,则继承。您还可以中断继承:例如,如果您希望使规则应用于大多数<,则可以在
table
元素上设置white-space: pre
/em> 的内容,并在不应用的行或单元格上设置white-space: normal
。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
because an
a
element is alway withinbody
andtd
by default inherits the property fromtr
.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
topre
(orpre-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 atable
element for example, if you wish to make the rule apply to most of the content, and setwhite-space: normal
on those rows or cells where it is not to be applied.用 替换空格有什么问题?这应该适用于任何元素并保留渲染输出中的空格。
What is wrong with replacing spaces by ? This should work inside any element and preserve the spaces in the rendered output.