Luka Luka - 6 months ago 9
CSS Question

Hide text if it doesn't fit in one line with CSS

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 whole text, not just extra lines). Otherwise show the text.

Can this be done with CSS?

Adding some additional elements in html that can help to accomplish this is acceptable.

Answer
  1. Place your text in an inline-block inner-wrapper with white-space: nowrap to prevent line breaks.
  2. Insert an empty inline-block pseudo-element before that inner-wrapper.
  3. When the inner-wrapper is wider than the outer-wrapper, it will be moved to the second line of the outer-wrapper.
  4. To hide it use 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>