How to word wrap text in a div


It is possible to wrap text in for example a div when the text exceeds your specified width.

We will be looking at two methods to wrap text. One with a simple adjustment of our CSS code. And one using a PHP function. For example when you created a div like this :
test.div {
width: 350px;
}

<div class="test"></div>

We can change our CSS to 'cleanly' break words to fit the given width.

test.div {
word-wrap: break-word;
width: 350px;
}

<div class="test"></div>

The second method uses a PHP built-in function named: wordwrap(). This function requires at least one parameter. It breaks line using a default '\n' break paramater.

Example 1. Wordwrap() standard no additional paramaters :
$string = 'This string needs to be wrapped';
$string = wordwrap($string);

echo '<div>' . $string . '</div>';

Wordwrap has a few extra paramters. The second paramater in the next example sets the width. And the third defines which characters to wrap with.


Example 2. Wordwrap() with a few additional paramters :
$string = 'This string needs to be wrapped';
$string = wordwrap($string, 350, "<br />");

echo '<div>' . $string . '</div>';




Posted by James on 2009-11-13 in the category " html "