white-space 是 CSS 中的一个属性,它用于指定如何处理元素中的空白(包括空格、制表符和换行符)。这个属性可以帮助你控制文本的布局,特别是在处理文本折行和空格方面。下面是 white-space 属性的几个常见取值及其作用的详细描述和代码示例。
-
normal:- 这是默认值。
- 连续的空白符会被合并。
- 文本会在允许的断点处自动换行。
<p style="white-space: normal;"> This is an example with extra spaces and a new line here to demonstrate normal. </p> -
nowrap:- 连续的空白符会被合并。
- 文本不会自动换行,即使在允许的断点处也不会换行。
<p style="white-space: nowrap;"> This is an example with extra spaces and it will not wrap even if it's too long. </p> -
pre:- 连续的空白符会被保留。
- 文本只会在遇到换行符或者
<br>标签时换行。
<p style="white-space: pre;"> This is an example with extra spaces and it respects new lines. </p> -
pre-wrap:- 连续的空白符会被保留。
- 文本会在遇到换行符、
<br>标签,或者达到容器边界时换行。
<p style="white-space: pre-wrap;"> This example respects both extra spaces and it wraps when needed. </p> -
pre-line:- 连续的空白符会被合并。
- 文本会在遇到换行符、
<br>标签,或者达到容器边界时换行。
<p style="white-space: pre-line;"> This example merges extra spaces but respects new lines and wraps. </p>
每个值的作用和表现可以通过这些示例在网页上直观地观察到。通过调整这个属性,你可以精确地控制文本的显示方式,使其更适合你的网页设计。
English version
white-space is a CSS property that specifies how whitespace (including spaces, tabs, and new line characters) inside an element is handled. This property helps control the layout of text, particularly in terms of text wrapping and space handling. Below are detailed descriptions and code examples for several common values of the white-space property.
-
normal:- This is the default value.
- Consecutive whitespace characters are collapsed.
- Text automatically wraps at allowed break points.
<p style="white-space: normal;"> This is an example with extra spaces and a new line here to demonstrate normal. </p> -
nowrap:- Consecutive whitespace characters are collapsed.
- Text does not wrap, even at allowed break points.
<p style="white-space: nowrap;"> This is an example with extra spaces and it will not wrap even if it's too long. </p> -
pre:- Consecutive whitespace characters are preserved.
- Text wraps only at newline characters or
<br>tags.
<p style="white-space: pre;"> This is an example with extra spaces and it respects new lines. </p> -
pre-wrap:- Consecutive whitespace characters are preserved.
- Text wraps at newline characters,
<br>tags, or when it reaches the container's boundary.
<p style="white-space: pre-wrap;"> This example respects both extra spaces and it wraps when needed. </p> -
pre-line:- Consecutive whitespace characters are collapsed.
- Text wraps at newline characters,
<br>tags, or when it reaches the container's boundary.
<p style="white-space: pre-line;"> This example merges extra spaces but respects new lines and wraps. </p>
The effect and behavior of each value can be visually observed on a webpage through these examples. By adjusting this property, you can precisely control the display of text to better suit your web design needs.