+22  A: 

Two fixes:

  1. overflow:scroll -- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden -- just cuts off any overflow. It means people can't read the content though.

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-word doesn't appear to work in Firefox).

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

Edit 2 (to address your comment below):

Start off using the CSS overflow property isn't perfect but it stops designs breaking. Apply overflow:hidden first. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:auto or overflow:scroll instead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenator a look in (as mentioned below).

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

Oli
with text-overflow:ellipsis; text can be cut of nicely.
porneL
text-overflow:ellipsis is IE-only (and by extension, non-standard).
Oli
+6  A: 

Do you mean that, in browsers that support it, word-wrap: break-word does not work ?

If included in the body definition of the stylesheet, it should works throughout the entire document.

If overflow is not a good solution, only a custom javascript could artificially break up long word.

Note: there is also this <wbr> Word Break tag. This gives the browser a spot where it can split the line up. Unfortunately, the <wbr> tag doesn't work in all browsers, only Firefox and Internet Explorer (and Opera with a CSS trick).

VonC
+17  A: 

You can make it possible to split long words by inserting soft hyphen (&shy;).

averyvery&shy;longword

may be rendered as

averyverylongword

or

averyvery-
longword

(Use zero-width space character if you don't want visible hyphen)

A nice regular expression can ensure you won't be inserting them unless neccessary:

/([^\s-]{5})([^\s-]{5})/ → $1&shy;$2
porneL
Please elaborate :)
Ace
Cool! According to wikipedia, you can get a zero-width space with ​ -- since you brought it up, do you know a less-ugly escape code for it? I'll memorize 8203 if I have to, but...
ojrac
@ojrac — That depends on whether you think ​ is "less ugly" or not. :-) AFAIK, there's no "word entity" for zero-width space.
Ben Blank
Well, #x200B is easier to remember. Good enough.
ojrac
You can use something like TextExpander (http://www.smileonmymac.com/TextExpander/) to give your names to any string or character.
porneL
That's nice, but is not a solution to the initial problem.
Albus Dumbledore
+6  A: 

I just found out about hyphenator from this question. That might solve the problem.

dylanfm
It made howWouldYourSiteDealWithCommentsLikeThisOne look nice and manageable. Very cool.
ojrac
+1  A: 

The solution I usually use for this problem is to set 2 different css rules for IE and other browsers:

word-wrap: break-word;

woks perfect in IE, but word-wrap is not a standard css property. It's a Microsfot specific property and doesn't work in Firefox.

For Firefox, the best thing to do using only css is to set the rule

overflow: hidden;

for the element that contains the text you want to wrap. It doesn't wrap the text, but hide the part of text that go over the limit of the container. It can be a nice solution if is not essential for you to display all the text (i.e. if the text is inside an <a> tag)

alexmeia
+2  A: 

HYPHENATOR is the right answer (given above). The real problem behind your question is that web browsers are still (in 2008) extremely primitive that they do not have a hyphenation-feature. Look, we are still on the early beginnings of computer usage - we have to be patient. As long as designers rule the web world we will have a hard time waiting for some real useful new features.

Snaky Love
+5  A: 

howWouldYourSiteDealWithCommentsLikeThisOnelanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogochLlanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogochLlanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogochLlanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogochwyngyllgogerychwyrndrobwllllantysiliogogogochLlanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogochLlanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogochLlanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

Edward Tanguay
See the edit I'm about to make on my earlier answer.
Oli
See, I think this example shows why the super-long-word behavior in div's and css is preferable to tables. That one word would totally screw up the layout of the rest of the page, if this were done in tables.
bigmattyh
+1  A: 

Why not use some js to get the length of the overall string and for every say 64 characters insert a <br /> character intot he string? Especially if you do it before inserting it into a database?

fossildesigns
+1  A: 

Yeah, if it is possible, setting an absolute width and setting "overflow : auto" works well.

John Gietzen
+9  A: 

This is a complex issue, as we know, and not supported in any common way between browsers. Most browsers don't support this feature natively at all.

In some work done with HTML emails, where user content was being used, but script is not available (and even CSS is not supported very well) the following bit of CSS in a wrapper around your unspaced content block should at least help somewhat:

.word-break {
  /* The following styles prevent unbroken strings from breaking the layout */
  width: 300px; /* set to whatever width you need */
  overflow: auto;
  white-space: -moz-pre-wrap; /* Mozilla */
  white-space: -hp-pre-wrap; /* HP printers */
  white-space: -o-pre-wrap; /* Opera 7 */
  white-space: -pre-wrap; /* Opera 4-6 */
  white-space: pre-wrap; /* CSS 2.1 */
  white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
  word-wrap: break-word; /* IE */
  -moz-binding: url('xbl.xml#wordwrap'); /* Firefox (using XBL) */
}

In the case of Mozilla-based browsers, the XBL file mentioned above contains:

<?xml version="1.0" encoding="utf-8"?>
<bindings xmlns="http://www.mozilla.org/xbl" 
          xmlns:html="http://www.w3.org/1999/xhtml"&gt;
  <!--
  More information on XBL:
  http://developer.mozilla.org/en/docs/XBL:XBL_1.0_Reference

  Example of implementing the CSS 'word-wrap' feature:
  http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/
  -->
  <binding id="wordwrap" applyauthorstyles="false">
    <implementation>
      <constructor>
        //<![CDATA[
        var elem = this;

        doWrap();
        elem.addEventListener('overflow', doWrap, false);

        function doWrap() {
          var walker = document.createTreeWalker(elem, NodeFilter.SHOW_TEXT, null, false);
          while (walker.nextNode()) {
            var node = walker.currentNode;
            node.nodeValue = node.nodeValue.split('').join(String.fromCharCode('8203'));
          }
        }
        //]]>
      </constructor>
    </implementation>
  </binding>
</bindings>

Unfortunately, Opera 8+ don't seem to like any of the above solutions, so JavaScript will have to be the solution for those browsers (like Mozilla/Firefox.) Another cross-browser solution (JavaScript) that includes the later editions of Opera would be to use Hedger Wang's script found here: http://www.hedgerwow.com/360/dhtml/css-word-break.html

Other useful links/thoughts:

Incoherent Babble » Blog Archive » Emulating CSS word-wrap for Mozilla/Firefox
http://blog.stchur.com/2007/02/22/emulating-css-word-wrap-for-mozillafirefox/

[OU] No word wrap in Opera, displays fine in IE
http://list.opera.com/pipermail/opera-users/2004-November/024467.html
http://list.opera.com/pipermail/opera-users/2004-November/024468.html

Neil Monroe
+1  A: 

If you have this -

  <style type="text/css">
      .cell {
            float: left;
            width: 100px;
            border: 1px solid;
            line-height: 1em;
      }
  </style>

  <div class="cell">TopLeft</div>
  <div class="cell">TopMiddlePlusSomeOtherTextWhichMakesItToLong</div>
  <div class="cell">TopRight</div>
  <br/>
  <div class="cell">BottomLeft</div>
  <div class="cell">BottomMiddle</div>
  <div class="cell">bottomRight</div>

just switch to a vertical format with containing divs and use min-width in your CSS instead of width -

  <style type="text/css">
      .column {
            float: left;
            min-width: 100px;
      }
      .cell2 {
            border: 1px solid;
            line-height: 1em;
      }
  </style>

  <div class="column">
      <div class="cell2">TopLeft</div>
      <div class="cell2">BottomLeft</div>
  </div>
  <div class="column">
      <div class="cell2">TopMiddlePlusSomeOtherTextWhichMakesItToLong</div>
      <div class="cell2">BottomMiddle</div>
  </div>
  <div class="column">
      <div class="cell2">TopRight</div>
      <div class="cell2">bottomRight</div>
  </div>
  <br/>

Of course, if you are displaying genuine tabular data it is ok to use a real table as it is semantically correct and will inform people using screen readers that is supposed to be in a table. It is using them for general layout or image-slicing that people will lynch you for.

Dan Brown
+1  A: 

"word-wrap: break-word" works in Firefox 3.5 http://hacks.mozilla.org/2009/06/word-wrap/

mb21
A: 

use the style "word-break:break-all". I know it works on tables.

sanimalp
+1  A: 

Need to set "table-layout: fixed” for word-wrap to work

Aleks
Thank you for this! Word-wrap: break-word; will not otherwise work for tables.
bilygates
+1  A: 

Just checked IE 7, Firefox 3.6.8 Mac, Firefox 3.6.8 Windows, and Safari:

word-wrap: break-word;

works for long links inside of a div with a set width and no overflow declared in the css:

consumeralerts_leftcol{

float:left;
width: 250px;
margin-bottom:10px;
word-wrap: break-word;

}

I don't see any incompatibility issues

Zac Imboden