如何在CSS中保留空格但忽略换行?

20

CSS-3中的white-space属性有pre-wrappre-line两个值,前者会保留空格和换行,并在必要时进行换行,后者会折叠空格但保留换行,并在必要时进行换行。

然而,它没有同时保留空格和折叠换行,同时仍然在必要时进行换行的值。

是否有其他CSS属性的组合可以实现这种效果?

例如:

This  example
code
should     render
on  one  line  but
with spaces     intact.

应该看起来像:

This  example code should     render on  one  line  but with spaces     intact.

2
没有纯CSS。 在这方面,“white-space”特别缺乏。 你能用JavaScript吗? - Mr Lister
这似乎不太可能成为规范的一部分。我想不出一个单一的用例,这将是有帮助的,但你仍然应该能够通过一些非常简单的JavaScript来实现它。 - Joseph Marikle
1
我唯一能想到的方法是使用JavaScript:https://jsfiddle.net/jmarikle/co9wqjmp/2 - Joseph Marikle
1
@JosephMarikle 你的意思是用空格替换换行符。https://jsfiddle.net/MrLister/co9wqjmp/4/ - Mr Lister
或者,你可以将空格硬编码为非断行空格,这样你甚至不需要JavaScript。 https://jsfiddle.net/MrLister/xc5nmpuj/2/ - Mr Lister
显示剩余6条评论
1个回答

10
你的问题的答案:不能仅使用CSS来解决它 (可证明 通过 white-space)。

behaviors of all the different values for white-space prop 没有像这样的行:collapse | preserve | ...

唯一的方法是使用JavaScript

document.body.innerHTML = document.body.innerHTML.replace(/\n/g, '');
html {
  white-space: pre-wrap;
}
This  example
code
should     render
on  one  line  but
with spaces     intact.

硬编码方法


第一种方法

* {
  white-space: pre-wrap;
}

br {
    display: none;
}
This  example<br/>code<br/>should     render<br/>on  one  line  but<br/>with spaces     intact.<br/>


2nd

This&nbsp; example
code
should &nbsp; &nbsp; render
on&nbsp; one&nbsp; line&nbsp; but
with spaces &nbsp; &nbsp; intact.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接