📅  最后修改于: 2023-12-03 15:00:05.971000             🧑  作者: Mango
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.
white-space
normal
The white-space
property accepts the following values:
normal
: The default value. Sequences of white space are collapsed, and line breaks occur at block boundaries or as dictated by the wrap
property.pre
: Sequences of white space are preserved. Line breaks and spaces are rendered exactly as they appear in the HTML code.nowrap
: Sequences of white space are collapsed. Line breaks are ignored, and the text does not wrap.pre-wrap
: Sequences of white space are preserved. Line breaks are rendered, and the text wraps when necessary.pre-line
: Sequences of white space are collapsed. Line breaks are rendered, and the text wraps when necessary.break-spaces
: Similar to pre-wrap
, but sequences of white space are broken at line breaks if they exceed the available width.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.
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.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.