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.
If you want to restrict it to one line, use white-space: nowrap; on the div.
You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <span> element is not visible, but it maintains its position on the page. Removing the hidden attribute makes it re-appear.
If you only want to show a single line of text in a fixed width div, give white-space:nowrap a go. Together with overflow:hidden it will force your browser not to break the line and crop the view to your forced width.
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>
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With