Hide text if it doesn't fit in one line with CSS
- Place your text in an inline-block inner-wrapper with
white-space: nowrap
to prevent line breaks. - Insert an empty inline-block pseudo-element before that inner-wrapper.
- When the inner-wrapper is wider than the outer-wrapper, it will be moved to the second line of the outer-wrapper.
- To hide it use
overflow: hidden
, and set the same value toheight
andline-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>
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.