【问题标题】:Truncating text with "text-overflow: ellipsis"用“文本溢出:省略号”截断文本
【发布时间】:2016-10-18 07:18:22
【问题描述】:

我有一个模块:

.container {
  width: 250px;
  height: 50px;
  background: #fffff3;
}
.truncate {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
<div class="container">
  <p class="truncate">
    <span>Some loooooooooooong name</span>
    :
    <span>1.7m</span>
    m Tall
  </p>
</div>

应该呈现为:

一些客户姓名:1.7m 高

我希望它被截断,这样如果名称太长,它看起来像:

一些长名字……:1.7m 高

我尝试过使用上面的 truncate 类,但它看起来像这样:

一些 looooooooooooong 的名字......

用户高度离开屏幕。我能做些什么来纠正这个问题?

【问题讨论】:

  • 有什么问题?高度?然后删除height: 50px;?
  • @nicael - 我相信 OP 是指文字 1.7m Tall by height
  • 啊,我明白了,谢谢@j08691。
  • @nicael 道歉没有说清楚!

标签: html css


【解决方案1】:

您需要为名称元素设置省略号,要使其正常工作,您还需要一个固定的width,因为它是一个&lt;span&gt;,您还需要更改display

.container {
  width: 250px;
  height: 50px;
  background: #fffff3;
}
.truncate {
  display: inline-block;
  vertical-align:middle;
  width: 120px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
<div class="container">
  <p>
    <span class="truncate">Some Looooongggg nameee</span>
    :
    <span>1.7 </span>
    M Tall
  </p>
</div>

【讨论】:

    【解决方案2】:

    尝试使用 flexbox 布局,并仅在第一个 span 上设置省略号。它还支持跨度和纯文本的动态长度。

    .truncate {
      display: flex;
      align-items: center; /* vertically center text */
      white-space: nowrap;
      width: 250px;
      height: 50px;
      padding: 0 8px 0 4px;
      background: gold;
    }
    .truncate span {
      min-width: 0;
      padding: 0 4px;
    }
    .truncate span:first-child {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      flex: 1; /* to take as much space as available */
    }
    <p class="truncate">
      <span>Looooooooooooooooooooooong name</span> :
      <span>1.7m</span> M Tall
    </p>

    【讨论】: