HTML 元素内的空白主要包含这三个:Space(空格)、Enter(回车)、Tab(制表符)。

这个属性指定了两件事:

  • 空白字符是否合并?空白字符如何合并?
  • 是否换行?如何换行?

在日常开发中,对于文字的空格和换行,默认的逻辑是:

  • 每一处的空格、回车、制表符都合并成一个空格。
  • 文字超过一行时,会自动换行。

带着默认的逻辑,一起来看看该属性的其他配置。

normal(默认)

每一处的空格、回车、制表符都合并成一个空格,文本自动换行。


prevent

normal(default)

动手试试看

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="app">There are three spaces after this   .There is a Enter after this
.There is a Tab after this        .</div>
  <style>
    .app {
      width: 250px;
      white-space: normal;
      background: pink;
    }
  </style>
</body>
</html>

nowrap

与 normal 的区别:文本不会自动换行。

每一处的空格、回车、制表符都合并成一个空格,文本不会自动换行。


prevent

nowrap

动手试试看

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="app">There are three spaces after this   .There is a Enter after this
.There is a Tab after this        .</div>
  <style>
    .app {
      width: 250px;
      white-space: nowrap;
      background: pink;
    }
  </style>
</body>
</html>

pre

文本原样输出,文本不换行。


prevent

动手试试看

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="app">There are three spaces after this   .There is a Enter after this
.There is a Tab after this        .</div>
  <style>
    .app {
      width: 250px;
      white-space: pre;
      background: pink;
    }
  </style>
</body>
</html>

pre-wrap

与 pre 的区别:文本会自动换行。

文本原样输出,文本会自动换行。

动手试试看


prevent

pre-wrap

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="app">There are three spaces after this   .There is a Enter after this
.There is a Tab after this        .</div>
  <style>
    .app {
      width: 250px;
      white-space: pre-wrap;
      background: pink;
    }
  </style>
</body>
</html>

pre-line

每一处空格、制表符合并成一个空格,回车不变,文本自动换行。

动手试试看


prevent

pre-line

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
    <div class="app">There are three spaces after this   .There is a Enter after this
.There is a Tab after this        .</div>
  <style>
    .app {
      width: 250px;
      white-space: pre-line;
      background: pink;
    }
  </style>
</body>
</html>

Steven
38 声望3 粉丝