在text-overflow: ellipsis样式下如何为省略号添加样式?

13

如何对text-overflow: ellipsis中的省略号进行样式设置?

例如可以加粗省略号使其显示为'Lorem Ips ...'。


我建议使用 ::after - Praveen Kumar Purushothaman
3个回答

18

这个答案的启发,以下是一种样式省略号的方法。

这个解决方案的缺点是:

  1. 您必须重新分配默认的文本样式
  2. 您需要一个更多的<span>元素(或其他元素)

.text-overflow
{
  color: blue;
  font-weight: bold;
  font-size: 20px;

  overflow: hidden;
  text-overflow: ellipsis;
  width: 100px;
  white-space: nowrap;
}

.text-overflow > span
{
  font-weight: normal;
  color: black;
  font-size: 14px;
}
<div class="text-overflow"><span>Here is some very nice text indeed. So this is getting long</span></div>


我猜我误解了你的问题。抱歉 ;). .text-overflow 的属性被应用于其中每一个内容。 <span> 元素覆盖了这个默认样式,因此其内部文本的字体不是蓝色的。我不确定省略号是如何应用的,但是由于 text-overflow 的行为绑定在 .text-overflow 上,我猜实现类似于 .text-overflow::after 或其他伪元素。由于伪元素位于 <span> 外部,所以默认属性被应用。 - Nico O
您的样式表中没有找到任何 .text-overflow::after 的 CSS 代码? - Praveen Kumar Purushothaman
1
@PraveenKumar 浏览器会自动添加 text-overflow: ellipsis; 属性的 ...,因此您不需要使用 ::after - Dmiters
1
@DmitryNarkevich 等等。我知道这个。我一年前问过这个问题... :P - Praveen Kumar Purushothaman
1
@PraveenKumar 哎呀,哈哈,我没看到日期。 - Dmiters
显示剩余2条评论

2
我建议使用:after,但这可能会替换掉没有省略号的内容。

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  position: relative;
}
.truncate::after {
  display: block;
  font-weight: bold;
  content: "...";
  position: absolute;
  bottom: 0;
  right: 0;
  background: #fff;
}
<div class="truncate">You may be starting to notice a trend from my recent articles here on HTML5 Hub. I’m a JS snob by trade, but by association I have to deal with my fair share of CSS issues. So, as an “outsider” looking in, I’m taking this opportunity to highlight some of the big “pain points” that CSS causes for various basic tasks in web dev. It’s not really intended as a criticism of the technology per se, but more a rallying cry to ask for standard solutions which remove our hacks.</div>

这并不是一种防黑的方法,但是我有几分建议。


这种方法的唯一问题是,即使没有截断任何内容,它也会添加“...”。 - allejo
@allejo 没错,你说得对... :( 这就是为什么我说这不是一个无懈可击的方法! - Praveen Kumar Purushothaman

-1
另一种方法是使用一个带有 span 元素的包装器,如下所示:

.text-overflow {
  font-size: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 200px;
  white-space: nowrap;
}

.style-text {
  font-size: 20px;
}
<div class="text-overflow">
  <span class="style-text">
    text that is styled and styled and styled
  </span>
</div>


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