CSS: white-space Line Break
white-space Property
The
white-space property controls
line break at whitespace positions, and whether repeated whitespaces are collapsed into one single whitespace.
white-space: normal-
- Newline character is changed to a space.
- Repeated spaces shrink into a single one.
- Long line is wrapped.
(Like in
ptag.) white-space: pre-
- Newline character force a wrap.
- White space sequences are shown as they are.
- No auto line wrap.
(Like in
pretag.)This is very useful, when you have poem, song lyrics, or code, you want line wrap at newline positions, and no need to add
brtag at the end of every line..x { white-space: pre; } white-space: pre-wrap-
- Newline character force a wrap.
- Long line is automatically wrapped.
- Repeated spaces are NOT shrinked into just one space.
This is very useful for computer code, even better than “pre” tag, 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.
// Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, “and what is the use of a book,” thought Alice “without pictures or conversation?”. console.log( 3 ) white-space: pre-line-
Like
pre-wrap, but repeated spaces are shrinked into just one space. white-space: break-spaces-
Same as
pre-wrap, except that:- Any sequence of preserved white space always takes up space, including at the end of the line.
- A line breaking opportunity exists after every preserved white space character, including between white space characters.
- Such preserved spaces take up space and do not hang, and thus affect the box's intrinsic sizes (
min-contentsize andmax-contentsize).
white-space: nowrap-
- Repeated spaces shrink into a single one.
- Newline char is changed to space.
- The element's width has no effect on line wrapping.
To force a wrap, use HTML “br” tag.
Summary:
| respect newline char | preserve spaces and tabs | wrap long line | End-of-line spaces | |
|---|---|---|---|---|
normal | no | no | ✅ | Remove |
pre | ✅ | ✅ | no | Preserve |
pre-wrap | ✅ | ✅ | ✅ | Hang |
pre-line | ✅ | no | ✅ | Remove |
break-spaces | ✅ | ✅ | ✅ | Wrap |
nowrap | no | no | no | Remove |
Non-Breaking Whitespace
To prevent a line wrap at positions you do not want to happen, use the Unicode character named NO-BREAK SPACE.
The HTML entity is .