在 HTML 页面中,即使使用 white-space: pre;
,rtl
和 ltr
文本交界处的空白也会折叠在 CSS 中。
我想在上下文中显示给定语料库中给定单词的所有出现。事件应出现在中心,前后文本应出现在左右两侧。封闭的文本应该向左和向右溢出,以便随着窗口宽度的改变,或多或少的上下文是可见的,用省略号剪裁,如下所示:
... text that precedes the occurrence and text that follows it ...
... and here is one more occurrence which is also centered ...
一个解决方法是在中心“出现”范围的开头包含一个空格(如我的 JSFiddle 中的第一个示例),但我认为这并不优雅。是否有更简洁的方法来强制前面文本中的最后一个空白正确显示?
p {
display: flex;
white-space: pre;
}
span {
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
flex-basis: 50%;
}
span:first-child {
text-align: right;
direction: rtl;
}
span.centre {
font-weight: bold;
flex-shrink:0;
flex-basis: auto;
}
span:last-child {
text-align: left
}
<div>
<p><span>long piece of text that comes before an </span><span class="centre">occurrence</span><span> of a word in a given corpus, and that I want to show centered...</span></p>
<p><span>text that precedes a completely different </span> <span class="centre">occurrence</span><span> of the same word elsewhere in the same corpus...</span></p>
<p><span>It makes sense to consider that the word </span><span class="centre">occurs</span><span> should also be included since it has the same root as ...</span></p>
</div>
最佳答案
在不影响 html 的情况下,您可以使用 CSS 在 :before
伪元素中放置一个空格。您还可以将它添加到 :after
,这样即使您的文本在标签内没有空格,空格也会在单词的两边都可见。
https://jsfiddle.net/79rc15wp/2/
p {
display: flex;
white-space: pre;
}
span {
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
flex-basis: 50%;
}
span:first-child {
text-align: right;
direction: rtl;
}
span.centre {
font-weight: bold;
flex-shrink:0;
flex-basis: auto;
}
span.centre:before {
content: " ";
}
span:last-child {
text-align: left
}
<div>
<p><span>long piece of text that comes before an </span><span class="centre">occurrence</span><span> of a word in a given corpus, and that I want to show centered...</span></p>
<p><span>text that precedes a completely different </span> <span class="centre">occurrence</span><span> of the same word elsewhere in the same corpus...</span></p>
<p><span>It makes sense to consider that the word </span><span class="centre">occurs</span><span> should also be included since it has the same root as ...</span></p>
</div>
关于CSS 空白在 rtl 和 ltr 文本相遇的地方折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52589862/