CSS White Space
The CSS white-space
property is used to control how whitespace characters (spaces, tabs, and line breaks) are handled within an element’s content. It allows you to specify whether whitespace should be preserved, collapsed, or wrapped.
The white-space
property can take one of the following values:
normal
(default): This value collapses consecutive whitespace characters into a single space and wraps the text to fit within the container’s width. Line breaks within the content are also treated as spaces.nowrap
: This value collapses consecutive whitespace characters, but it does not allow text to wrap to the next line. The text will be displayed on a single line, and any overflow will be hidden.pre
: This value preserves whitespace characters exactly as they appear in the source code. Line breaks and spaces will be displayed as they are in the content.pre-wrap
: This value preserves whitespace characters likepre
, but it allows text to wrap to the next line if it exceeds the container’s width.pre-line
: This value collapses consecutive whitespace characters likenormal
, but it preserves line breaks. It allows text to wrap to the next line if it exceeds the container’s width.
Example:
p {
white-space: nowrap;
}
In this example, the text inside all <p>
elements will be displayed on a single line without wrapping.
The white-space
property is particularly useful when dealing with code snippets, pre-formatted text, and maintaining the appearance of whitespace-sensitive content.
By using white-space
effectively, you can control how text is displayed and wrapped within elements, ensuring that it matches your desired layout and formatting requirements.
Keep in mind that white-space
affects only the presentation of whitespace characters within an element’s content; it does not affect the spacing and layout of the element itself. For adjusting spacing around an element, you would typically use the margin
and padding
properties.