我有一个div
元素,其中包含一些文字。此元素具有固定宽度。如果文本太长以至于它不能放在一行中,我想隐藏该文本(整个文本,而不仅仅是额外的行)。否则显示文字。
可以用CSS完成吗?
在html中添加一些有助于实现此目的的其他元素是可以接受的。
答案 0 :(得分:12)
white-space: nowrap
的内联块内包装中,以防止换行。overflow: hidden
,并将相同的值设置为height
和line-height
。
.outer-wrapper {
overflow: hidden;
height: 1.2em;
line-height: 1.2em;
border: 1px dotted black;
margin: 1em;
}
.outer-wrapper::before {
content: '';
display: inline-block;
}
.inner-wrapper {
display: inline-block;
white-space: nowrap;
}
<div class="outer-wrapper">
<div class="inner-wrapper">
this is a short line
</div>
</div>
<div class="outer-wrapper">
<div class="inner-wrapper">
this is a super long line of text that it is never ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever going to fit on a single line!
</div>
</div>
答案 1 :(得分:1)
如果您想隐藏额外的文字,可以执行以下操作:
div {
white-space: nowrap;
overflow: hidden;
max-width: 50em;
border: 1px dotted black;
}
&#13;
<p><br><br></p>
<div>
this is a super long line of text that it is never ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever going to fit on a single line!
</div>
&#13;
如果要完全隐藏整个元素,则需要使用JavaScript。 CSS没有办法&#34;检测&#34;如果文字太长。
答案 2 :(得分:1)
其他评论中提出的解决方案已经过时,今天,我们有一种简单的真正方法来使用text-overflow
。
注意:
text-overflow: string
仅在 Firefox 中工作。注释2:
text-overflow
仅在容器的溢出属性隐藏了值, scroll 或 auto 和white-space: nowrap;
。
.a {
white-space: nowrap;
width: 50px;
overflow: hidden;
text-overflow: clip;
border: 1px solid #000000;
}
.b {
white-space: nowrap;
width: 50px;
overflow: hidden;
text-overflow: ellipsis;
border: 1px solid #000000;
}
.c {
white-space: nowrap;
width: 50px;
overflow: hidden;
text-overflow: "----";
border: 1px solid #000000;
}
<h1>The text-overflow Property</h1>
<p>The following two divs contains a text that will not fit in the box.</p>
<h2>text-overflow: clip (default):</h2>
<div class="a">Hello world!</div>
<h2>text-overflow: ellipsis:</h2>
<div class="b">Hello world!</div>
<h2>text-overflow: "----" (user defined string):</h2>
<div class="c">Hello world!</div>
Here,您可以在this article中找到示例和更完整的说明。