clarkk
clarkk

Reputation: 27689

how to hide too long texts in div elements?

How can you hide the overflow in a div?

Here, the text wraps to a new line if it is longer than the div.

#truncateLongTexts {
    width: 50px;
    border: 1px solid black;
    overflow-y: hidden;
}
<div id="truncateLongTexts">
    test test test test
</div>

Upvotes: 38

Views: 95175

Answers (4)

jhunlio
jhunlio

Reputation: 2660

Maybe the CSS property text-overflow: ellipsis can help you out with that problem.

Consider this HTML and CSS below:

<div id="truncateLongTexts">
    test test test test
</div>
#truncateLongTexts {
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; /* This is where the magic happens. */
}

Upvotes: 47

DarthJDG
DarthJDG

Reputation: 16591

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.

You might also add text-overflow:ellipsis to avoid cutting words and letters in half, it adds a nice ... to the end to show you there's some bits missing. I'm not sure about the browser support though, and I've never tried this one.

Upvotes: 35

kapa
kapa

Reputation: 78681

You should specify a height for your div, overflow: hidden; can only hide the vertically overflowing content if there is some kind of defined height.


In other words:

Here the text just wraps down to a new line if the text is longer than the div

But how long is that div actually?


Please check out my jsFiddle demonstration that illustrates the difference.

Upvotes: 14

Alistair Laing
Alistair Laing

Reputation: 973

try overflow:none;

you didn't mention if you want scrollbars or not.

EDIT:

Sorry I meant overflow:hidden.

Upvotes: 0

Related Questions