在链接上使用text-overflow:ellipsis

43

我想在链接上使用text-overflow属性。对于段落,它可以工作,但对于链接则无效。

这是HTML代码:

<div>
  <ul>
    <li>
        <p>the text is too long</p>
    </li>   
    <li>
         <a href="javascript:alert('test')">the link is too long</a>
    </li>
  </ul>
</div>

这是CSS代码:

a {
  white-space: nowrap;
  width:50px; 
  overflow: hidden;
  text-overflow: ellipsis;

}
p {
  white-space: nowrap;
  width:50px; 
  overflow: hidden;
  text-overflow: ellipsis;
}

请参见http://jsfiddle.net/corinnekm/LLVDB/上的示例。

非常感谢您的帮助。

2个回答

82

<a> 标签是一个内联元素,你只能将省略号应用于块级元素,尝试使用 a {display: block;} 就可以了。


9

http://primercss.io/utilities/有一组CSS截断规则。 请参阅https://jsfiddle.net/illegs/g04L9xd6/

.css-truncate.css-truncate-target,
.css-truncate .css-truncate-target {
display: inline-block;
max-width: 50px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: top
}

.css-truncate.expandable.css-truncate-target,
.css-truncate.expandable.css-truncate-target,
.css-truncate.expandable:hover .css-truncate-target,
.css-truncate.expandable:hover.css-truncate-target {
max-width: 10000px !important
}

<span class="css-truncate expandable">
<span class="branch-ref css-truncate-target"><a href="javascript:alert('test')">the link is too long</a></span>


谢谢,@Gilles,你帮了我很多。 - eyalewin
这是一个好答案,但不幸的是,对于任何试图将其用于按钮而非链接的人来说,请注意Chrome bug会导致文本被截断而不是显示省略号。可以通过在答案中运行JSFiddle并将a标签更改为button标签来演示这一点。 https://bugs.chromium.org/p/chromium/issues/detail?id=107014 - Jim

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