white-space

The white-space property in CSS is used to control how white space inside an element is handled. It can influence how spaces, tabs, and line breaks are treated within an element. Defines how the element’s white space is handled.

Basic syntax

element {
    white-space: value;
}

Common white-space values

  • normal (default): Collapses white space and breaks lines as necessary within the element.
p {
    white-space: normal;
}

Extra spaces are ignored, and text wraps to the next line when needed. Sequences of spaces are combined into one. Line breaks are ignored.
he text content is wrapped.

  • nowrap: Collapses white space but prevents text from wrapping to the next line. Text will continue on the same line, which might cause overflow if the content is too wide.
p {
    white-space: nowrap;
}

The text content is not wrapped and remains on a single line.

  • pre: Preserves white space, and the text does not wrap unless there is a <br> tag or a newline in the source code.
pre {
    white-space: pre;
}

This value is often used with <pre> tags to maintain formatting in code snippets. The white space is exactly preserved.

  • pre-wrap: Preserves white space and allows text to wrap to the next line.
p {
    white-space: pre-wrap;
}

The white space is mostly preserved.

Sequences of spaces are preserved. Lines break on new lines, <br>, but also when reaching the end of the element

  • pre-line: Collapses consecutive white spaces but preserves line breaks.
p {
    white-space: pre-line;
}

Only new lines are preserved.

  • break-spaces: Similar to pre-wrap, but preserves all spaces and allows lines to break at any preserved white space.

Using white-space Effectively

  • Controlling line breaks:
    • Use nowrap to prevent line breaks within an element.
    • Use pre, pre-wrap, or pre-line to preserve or control line breaks.
  • Adjusting spacing between words:
    • Use word-spacing to increase or decrease the spacing between words.
  • Adjusting spacing between letters:
    • Use letter-spacing to increase or decrease the spacing between individual letters.

Examples

.container {
  width: 200px;
  border: 1px solid black;
}

.nowrap-text {
  white-space: nowrap;
}

.pre-text {
  white-space: pre;
}

.pre-wrap-text {
  white-space: pre-wrap;
}

.pre-line-text {
  white-space: pre-line;
}

Additional Tips

  • Combine properties: Use white-space, word-spacing, and letter-spacing together to achieve precise control over white space within an element.
  • Consider browser compatibility: Be aware of potential browser compatibility issues, especially for older browsers or specific values.
  • Experiment and adjust: Try different values and combinations to find the best approach for your specific needs.