📜  CSS white-space(1)

📅  最后修改于: 2023-12-03 15:00:05.971000             🧑  作者: Mango

CSS white-space

The white-space property in CSS is used to control how white space within an element is handled. It allows you to manipulate how line breaks, spaces, and tabs are rendered in a block-level element.

Quick Overview
  • Property: white-space
  • Initial value: normal
  • Applies to: Block-level elements and replaced elements
  • Inherited: Yes
  • Media: Visual
Property Values

The white-space property accepts the following values:

  1. normal: The default value. Sequences of white space are collapsed, and line breaks occur at block boundaries or as dictated by the wrap property.
  2. pre: Sequences of white space are preserved. Line breaks and spaces are rendered exactly as they appear in the HTML code.
  3. nowrap: Sequences of white space are collapsed. Line breaks are ignored, and the text does not wrap.
  4. pre-wrap: Sequences of white space are preserved. Line breaks are rendered, and the text wraps when necessary.
  5. pre-line: Sequences of white space are collapsed. Line breaks are rendered, and the text wraps when necessary.
  6. break-spaces: Similar to pre-wrap, but sequences of white space are broken at line breaks if they exceed the available width.
Usage

You can apply the white-space property to any block-level or replaced element using CSS selectors. For example:

p {
  white-space: pre;
}

code {
  white-space: nowrap;
}

This will set the white-space property to pre for all <p> elements, preserving spaces and line breaks. The white-space property for <code> elements will be set to nowrap, collapsing spaces and ignoring line breaks.

Example

Let's consider the following HTML code:

<div id="myDiv">
  This    is    a    sample    text    with    extra    spaces.
</div>

By applying CSS with different white-space values, the rendered output will be:

  • white-space: normal: This is a sample text with extra spaces.
  • white-space: pre: This is a sample text with extra spaces.
  • white-space: nowrap: Thisisasampletextwithextraspaces.
  • white-space: pre-wrap: This is a sample text with extra spaces.
  • white-space: pre-line: This is a sample text with extra spaces.
  • white-space: break-spaces: This is a sample text with extra spaces.
Conclusion

Understanding and using the white-space property in CSS allows you to control how white space is managed within a block-level element. By setting the appropriate value, you can control line breaks, spacing, and text wrapping, ensuring the desired rendering of content.