How to prevent text from overflowing in CSS?

Viewed 390808

How can I prevent text in a div block from overflowing in CSS?

div {
  width: 150px;
  /* what to put here? */
}
<div>This div contains a VeryLongWordWhichDoesNotFitToTheBorder.</div>

15 Answers

You can control it with CSS, there is a few options :

  • hidden -> All text overflowing will be hidden.
  • visible -> Let the text overflowing visible.
  • scroll -> put scroll bars if the text overflows

Hope it helps.

It's now the css property:

word-break: break-all

overflow: scroll ? Or auto. in the style attribute.

.NonOverflow {
    width: 200px; /* Need the width for this to work */
    overflow: hidden;
}
<div class="NonOverflow">
    Long Text
</div>

If your div has a set height in css that will cause it to overflow outside of the div.

You could give the div a min-height if you need to have it be a minimum height on the div at all times.

Min-height will not work in IE6 though, if you have an IE6 specific stylesheet you can give it a regular height for IE6. Height changes in IE6 according to the content within.

You can just set the min-width in the css, for example:

.someClass{min-width: 980px;}

It will not break, nevertheless you will still have the scroll-bar to deal with.

!! Hard coded tradoff ahead !! Depending on the surrounding code and the screen resolution this could lead to different / unwanted behaviour

If hidden overflow is out of the question and correct hyphenation is needed you could use the soft hyphen HTML entity where you want the word / text to break. This way you are able to predetermine a breaking point manually.

&shy;

The hyphen will only appear when the word needs to break to not overflow its surrounding container.

Example:

<div class="container">
  foo&shy;bar
</div>

Result if the container is wide enough and the text would not overflow the container:

foobar

Result if the container is to small and the text would actually overflow the container:

foo-
bar

.container{
  background-color: green;
  max-width: 30px;
}
Example 1 - container to small => text overflows container:

<div class="container">
  foobar
</div>

Example 2 - using soft hyphen => text breaks at predetermined break point:

<div class="container">
  foo&shy;bar
</div>

Example 3 - using soft hyphen => text still overflowing because the text before the soft hyphen is to long:

<div class="container">
  foobar&shy;foo
</div>

Further information: https://en.wikipedia.org/wiki/Soft_hyphen

Related