What is whitespacing?
To control the spacing of content in HTML, according to the source code we can use the white-space
property. It denotes the way spaces and new lines in the code are dealt with.
So before moving forward let's first see how HTML deals with whitespacing by default within it.
Consider the HTML below and take special note of the way the text is written with newlines and extra spaces at some locations.
<div>This is a line and
this is a new line and here we have a lot of spacing
but nonetheless HTML will chop off all extra spaces and newline characters
in the final output.
</div>
Now compare the source code and the output and see how they differ.
By default, HTML tends to condense down any sequence of white spaces and/or newline characters to one single space. This means that whether you have 2 spaces, 10 spaces, one newline or thousands of them; HTML will display it as one single space.
And this is just what happened with the example above. Extra spacing got chopped off to a single space.
The white-space property
Fortunately, using the property white-space
we can manipulate this normal behavior to match one of the following.
The values include:
normal
: (default) normal spacing where any number of spaces and newline characters are condensed down to a single value.nowrap
: causes the content not to wrap to a newline once it overflows.pre
: preserves the actual white spacing in the HTML.pre-wrap
: same aspre
, except for that it wraps a line once it overflows.pre-line
: only preserves newlines.
Following we illustrate each value in real action, starting with nowrap
.
nowrap
- no wrapping
By default HTML and CSS wraps text once it overflows in a line. The nowrap
value removes this default behavior and lets any overflowing line remain as it is.
See below to get a better idea.
div {white-space: nowrap}
As you can see all the text got condensed down to a single line with no wrapping.
pre
- preserve spacing
pre
serves to preserve the white spacing in the HTML. The way you write the HTML, will be the way it is displayed in the browser. Lines will remain as they are i.e won't be wrapped.
Following is an example of pre
whitespacing:
div {white-space: pre}
pre-wrap
- preserve and wrap
pre-wrap
works exactly the same as pre
except for that it causes any overflowing line to wrap as well - hence the name pre-wrap.
div {white-space: pre-wrap}
pre-line
- preserve lines only
pre-line
preserves new lines only, removing any extra sequences of spaces. Hence the name pre-line.
Consider the following example to understand what this means.
div {white-space: pre-line}
As you can clearly see, all the extra spaces in the second line have been removed as well as the indentation of the text. What is preserved are only new lines, that's it.