Friday 23 September 2011

CSS: word-wrap, how to use it

   


Word wrap is an almost obscure CSS property. It's rarely used, but it can save your day sometimes. So, to get to the point, which one of the two following boxes do you prefer?


ThisIsAVeryLongTextThatWon'tBreakUnlessForcedToDoSo

ThisIsAVeryLongTextThatWillBreakBecauseWasForcedToDoSo

I bet you prefer the second one. How to do it? Just one line of code! Follow me...


The two divs
Styling the two boxes is very simple. First of all, let's create two consecutive divs and assign them two classes. The first div will have a class called without_word_wrap, the second with_word_wrap. I'm sure you have noticed how inventive I am in assigning classes. But that's how we should do to remember what the class is actually doing.
<div class="without_word_wrap">
ThisIsAVeryLongTextThatWon'tBreakUnlessForcedToDoSo</div>
<br />
<div class="with_word_wrap">
ThisIsAVeryLongTextThatWillBreakBecauseWasForcedToDoSo</div>
Those are the two divs.

The style
It is very simple because we only need to use the word-wrap property which has just two possible values: normal or break-word. The rest is there just to make the two boxes more clear (background, border, text colour etc.).
<style type="text/css">
.with_word_wrap {
  word-wrap: break-word;
  background-color: red;
  color:white;
  width:200px;
  height:50px;
  padding:30px;
  border: solid 1px #000000;
}
.without_word_wrap {
  word-wrap: normal;
  background-color: red;
  color:white;
  width:200px;
  height:50px;
  padding:30px;
  border: solid 1px #000000;
}
</style>
As you can see, it is very simple and effective.

Compatibility
This time we shouldn't have any big problem with browser compatibility. The word-wrap property works in IE5.5+, Firefox 3.5+, and WebKit browsers (Opera and Safari).

Enjoy and let me know if it was useful somehow.

2 comments:

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.