I have a div
element which contains some text. This element has fixed width. If the text is so long that it cannot fit in one line, I want to hide that text (the wh
The solutions presented in other comments are out of date, today we have a really simple way to do this using text-overflow
.
Note: The
text-overflow: string
only works in Firefox.Note 2:
text-overflow
only occurs when the container's overflow property has the value hidden, scroll or auto andwhite-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 you can find an example and a more complete explanation in this article.
If you want to hide the extra text, you can do something like:
div {
white-space: nowrap;
overflow: hidden;
max-width: 50em;
border: 1px dotted black;
}
<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>
If you want to hide the entire element completely, you will need to use JavaScript. CSS has no way to "detect" if the text is too long.
white-space: nowrap
to prevent line breaks.overflow: hidden
, and set the same value to height
and 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>