CSS: Line Wrap Tutorial

, , …,
Want to master JavaScript in a week? Example based, to the point. Xah JavaScript Tutorial.

This page explains how to control the text wrapping in HTML/CSS.

CSS2 provides several ways to control text wrapping. The attribute is white-space. How the line wraps depends on its value. The default value for “p” and “div” tags is normal.

white-space: normal

<p style="white-space:normal">…</p>

This is the normal behavior of the paragraph tag <p>.

Note that white spaces are any of space, tab, and newline characters. You can always use <br> tag to force a line break.

white-space: pre

<p style="white-space:pre">…</p>

With white-space: pre, the behavior is the same as the <pre> tag.

pre is best used for showing computer program code, or poetry of short lines.

white-space: pre-wrap

<p style="white-space:pre-wrap; width:60ex">…</p>

With white-space:pre-wrap, it's like mix of pre, and normal.

This is very useful for computer code, even better than pre, because if you have a long line comment, it'll be wrapped in the display, but when user copies the code, there will not be extra newline. For example:

# python
# Here is a very long comment.  long01 long02 long03 long04 long05 long06 long07 long08 long09 long10 long11 long12 long13 long14 long15 long16 long17
print 5

white-space: pre-line

This is just like pre-wrap, except that repeated spaces are shrinked into just one space.

white-space: nowrap

<p style="white-space:nowrap; width:60ex">…</p>

Using “width”, “<br>”, “NO-BREAK SPACE”

A common way to control wrap for paragraphs is simply to use the “width”. Like this:

<p style="width:60ex">…</p>

That will limit the width to 60 “ex” unit. A “ex” unit is basically the height of the lowercase letter “x”. (note that this does not guarantee that your paragraph will have 60 characters per line, but usually slightly more. Exactly how many characters per line with width:60ex depends on the font used.)

You can always force a line break by using <br>.

To prevent a line wrap at positions you do not want to happen, use the Unicode character named NO-BREAK SPACE. Its decimal value is 160, hex is A0. The HTML entity is &nbsp;.

CSS3 「word-wrap: break-word」

CSS3 introduced several ways to control line breakes and white space. One of the new feature is word-wrap:break-word. It tells the browser to freely force a line break in the middle of a word.

here's a example:

<p style="width:5ex">loooooooooooooooooooooooooooong</p>

here's what your browser renders:

loooooooooooooooooooooooooooong

now, the same text but with break-work:

<p style="width:5ex; word-wrap:break-word">loooooooooooooooooooooooooooong</p>

here's what your browser renders:

loooooooooooooooooooooooooooong

http://www.w3.org/TR/2010/WD-css3-text-20101005/

Thanks to Dave for mentioning “word-wrap:break-word”.

blog comments powered by Disqus