添加 CSS

  • 将 <body> 元素的 text-align 属性设置为“center”。
  • 为 <h1> 添加颜色。
  • 为 <div> 元素使用设置为“pre”的 white-space 属性。
body {
  text-align: center;
}
h1 {
  color: #000000;
}
div {
  white-space: pre;
}

让我们看看我们的代码的结果。

使用 white-space 属性换行的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        text-align: center;
      }
      h1 {
        color: #000000;
      }
      div {
        white-space: pre;
      }
    </style>
  </head>
  <body>
    <h1>onitroad</h1>
    <div>
      Example 
      Example
    </div>
  </body>
</html>

接下来,我们将展示如何使用 display 属性换行。
我们需要设置 display:block 来将一个元素表示为一个块元素。
在以下示例中,我们将 display: block 设置为 <p> 元素内的 <span> 元素。

使用 display 属性换行的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      body {
        text-align: center;
      }
      h1 {
        color: #000000;
      }
      p span {
        display: block;
      }
    </style>
  </head>
  <body>
    <h1> 
      onitroad
    </h1>
    <p>
      <span>Example_1</span>
      <span>Example_2</span>
    </p>
  </body>
</html>

此外,我们可以使用回车符 (\A) 作为伪元素中的内容。

可以使用 ::before 和 ::after 伪元素添加新行。

使用 ::after 伪元素换行的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .line:after {
        content: '\A';
        white-space: pre;
      }
    </style>
  </head>
  <body>
    <h3>
      <span class="line">This is the first line</span>
      <span class="secondary-label">second line</span>
    </h3>
  </body>
</html>
在 CSS 中如何不使用 <br> 标签的情况下换行

有几种方法可以在不使用 <br> 标签的情况下换行。

为此,我们可以使用块级元素。

默认情况下,块级元素从新行开始(如果 CSS 规则没有覆盖默认行为)。
其中我们可以找到如何使内联元素从新行开始。

在此代码中,我们将使用以下属性:

  • white-space:使元素表现得像 <pre> 的 pre,
  • display: 用于将元素表示为块元素的块。

让我们看看如何使用 white-space 属性换行。

此属性指定必须如何处理元素内的空白。
空白可以是空格序列或者换行符。

创建 HTML

  • 使用 <h1> 和 <div> 元素。
<h1>onitroad</h1>
<div> 
  Example
  Example
</div>
日期:2020-06-02 22:14:58 来源:oir作者:oir