【问题标题】:Adding ... when text is too long in a div with only CSS [duplicate]添加 ... 当文本在只有 CSS 的 div 中太长时 [重复]
【发布时间】:2026-02-16 10:35:01
【问题描述】:

我想创建一个标签系统。当 div(标签)中的文本太长时,我会截断它并在最后添加“...”。是否有任何 CSS 解决方案可以做到这一点?

【问题讨论】:

  • 搜索“css ellipsis”。

标签: html css tags


【解决方案1】:

试试这个:

<div class='truncate'></div>



.truncate {
     width: 250px;
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
    }

【讨论】:

    【解决方案2】:

    您可以为此使用text-overflow: ellipsis。更多信息在代码的 cmets 中。

    div {
      width: 10em; /* the element needs a fixed width (in px, em, %, etc) */
      overflow: hidden; /* make sure it hides the content that overflows */
      white-space: nowrap; /* don't break the line */
      text-overflow: ellipsis; /* give the beautiful '...' effect */
    }
    &lt;div&gt;This is a text that is too long for this div.&lt;/div&gt;

    【讨论】:

    • 有没有办法在悬停/工具提示或类似的东西上显示全文?
    【解决方案3】:

    这是您所需的 css。

    .tag{
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 100px;
    }

    这里

    宽度可以更改为所需的大小。

    white-space 将确保文本在同一行。

    overflow:hidden 将隐藏多余的内容允许 text-overflow 添加点。

    文本溢出:省略号会加点

    【讨论】: