我发现那篇文章
https://justmarkup.com/log/2015/07/dealing-with-long-words-in-css/
我想知道如果它适合容器,如何强制显示整个单词:
例如
some long sentence
它可以显示为
some long s...
这个单词 sentence
不适合所以我想隐藏它并仅显示:
some long
我现在的CSS(它增加了 ...
)
.short {
max-width: 250px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
你可以试试这个:
.element{
display: block;
width: 100px;
overflow: hidden;
word-wrap: break-word;
text-overflow: ellipsis;
max-height: 16px;
line-height: 16px;
}
<div class="element">some long string</div>
哪里 max-height
:= line-height
:× <number-of-lines>
只需让文字溢出
.short {
max-width: 250px;
height: 1em;
overflow: hidden;
position: relative;
}
您可以将文本限制为一定数量的字符。然后,您必须找到空格字符的最后一个索引,并使用此索引再次限制文本。
这是一些示例代码:
function limitText(text, maxLength) {
if (text.length <= maxLength) {
return;
}
text = text.substr(0, maxLength);
var lastSpace = text.lastIndexOf(' ');
return text.substr(0, lastSpace) + '...';
}
limitText('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.', 20);
如果您只想限制单词数,可以使用此代码:
var maxWords = 4;
var text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
var newText = text.split(' ').slice(0, maxWords).join(' ');
尝试这个,
div{
white-space: nowrap;
width: 70px;
overflow: hidden;
}
div > p{
white-space: nowrap;
width: 70px;
overflow: hidden;
}
<div><p>some long sentences</p></div>
<div>some long sentences</div>