CSS 空白在 rtl 和 ltr 文本相遇的地方折叠

标签 css whitespace

在 HTML 页面中,即使使用 white-space: pre;rtlltr 文本交界处的空白也会折叠在 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>

JSFiddle

最佳答案

在不影响 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/

相关文章:

CSS:标准化一行缩略图之间的空间

vim - Vim 中 Tab 键 == 4 个空格并在大括号后自动缩进

keyboard - CTRL+M 和 Enter 一样吗?

xml - XSL 完全删除注释(包括空格)

jquery - Popup Jquery 适用于除 IE7 以外的所有浏览器

javascript - 如何使用 jquery 获取选择框选项中类的值

html - flex 调整内容 : center overwrite

html - 如何删除底部伪元素之后和之前的空格?

php - 压缩 HTML 标记中属性之间的空格

git - 应用 git 补丁时忽略上下文行中的空格差异