CSS: Line Wrap Tutorial

By Xah Lee. Date: . Last updated: .

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

white-space: normal

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

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

Note that white spaces are any of space, tab, and newline characters. You can always use <br> element 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> element.

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:500px">…</p>

Or you can use max-width. [see CSS: Units]

[see CSS: Computed Style]

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

Non-Breaking Whitespace

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;. [see HTML/XML Entity List]



Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog