我正在尝试使用 CSS 在我的长文本上显示一个省略号。当文本不包含空格时,这似乎工作正常,因此不能被打破(即换行),但当它包含空格时,省略号不会出现。
我的代码是:
<!DOCTYPE html>
<html>
<head>
<style>
span {
width: 150px;
display: inline-block;
border: 1px dotted blue;
height: 1em;
overflow: hidden;
text-overflow: ellipsis;
padding: 4px;
}
</style>
</head>
<body>
<div>
<span>
This is some long text that I want to have an ellipsis on.
</span>
</div>
<div>
<span>
afejaklfjefklafjeklfjeklfjeklfejfklejfkfjeklfjeklfejfklaejfeklfejfklejfklfejfkl
</span>
</div>
<body>
</html>
最佳答案
如果您添加 white-space:nowrap
省略号将会出现。原因是您的带空格的文本会在有空格的情况下换行,并且不需要省略号。如果您删除 overflow-hidden
并且文本将被换行显示,您可以看到它的实际效果。
span {
width: 150px;
display: inline-block;
border: 1px dotted blue;
height: 1em;
overflow: hidden;
text-overflow: ellipsis;
padding: 4px;
white-space: nowrap;
}
来自 doc
The text-overflow declaration allows you to deal with clipped text: that is, text that does not fit into its box. text-overflow comes into play only when: the box has overflow other than visible (with overflow: visible the text simply flows out of the box) the box has white-space: nowrap or a similar method of constraining the way the text is laid out. (Without this, the text would wrap to the next line)
关于css - 如何让省略号显示在CSS中的文本上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16782691/