在编写 HTML 时,你经常需要插入换行符。在地址、诗歌或文本超过可用浏览器宽度时,换行是必不可少的。如果你不插入换行符,则文本的格式会很奇怪。

在本教程中,我将通过一些示例向你展示如何在 HTML 代码中插入换行符,以便你可以开始正确使用它,并更好地设置文本格式。

基本 HTML 换行符语法

你可以使用 <br> 标签在 HTML 中插入换行符,这相当于键盘上的回车。

请注意,HTML 将忽略通过键盘返回键输入的换行符。

<br />

如果你想知道为什么上面的 <br> 标签中有一个正斜杠,当 HTML4 仍然被广泛使用时,斜杠很重要。使用 HTML5,你不再需要在其中添加斜杠。但两种方式的效果一样。

如果你使用的是 prettier 之类的代码格式化程序,则即使你没有将斜杠放入其中,它也会在你保存或粘贴时始终插入斜杠。

如何在地址中插入换行符

例如,当你在信件上书写地址时,换行符很重要。

这是一个没有换行符的地址示例

没有换行符(<br> 标签)的地址如下所示:

<p>
     The White House, 1600 Pennsylvania Avenue NW Washington, DC 20500, USA.
</p>

我添加了一些 CSS 代码,使用 Flexbox 把所有内容居中,并使文本更大一点:

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    font-size: 3rem;
    max-width: 1000px;
    margin: 0 auto;
}

在浏览器中显示如下:

address-without-line-breaks

这是一个有换行符的地址

这就是我们如何添加换行符,以正确设置地址的格式:

<p>
    The White House <br />
    1600 Pennsylvania Avenue <br />
    NW Washington, DC <br />
    20500 <br />
    USA
</p>

在浏览器中显示如下:

address-with-line-breaks

如何在诗歌中添加换行符

诗歌通常是用简短的断句写成,以创建视觉层次结构,格式很漂亮。

因此,如果你想在 HTML 代码中写一首诗,<br> 标签可以让你更轻松地进行格式化过程。

一首没有换行符的诗

<p>
      I dabbled around a lot when I decided to learn to code 
      I went from A to Z with resources 
      When I decided to make my own things 
      I discovered I've been in the old all while 
      So I remained a novice in coding 
      But then I found freeCodeCamp 
      I got my hands on the platform 
      I went from novice to ninja in coding 
     And now I'm a camper for life
</p>

在浏览器中显示如下:

poem-without-line-break

你可以看到这首诗没有视觉层次,它的格式不正确,所以它作为一首诗是不可读的。

一首有换行符的诗

<p>
      I dabbled around a lot when I decided to learn to code <br />
      I went from A to Z with resources <br />
      When I decided to make my own things <br />
      I discovered I've been in the old all while <br />
      So I remained a novice in coding <br />
      But then I found freeCodeCamp <br />
      I got my hands on the platform <br />
      I went from novice to ninja in coding <br />
      And now I'm a camper for life <br />
</p>

我还在 CSS 中稍微更改了字体大小:

body {
   display: flex;
   align-items: center;
   justify-content: center;
   height: 100vh;
   font-size: 2.5rem;
   max-width: 1000px;
   margin: 0 auto;
}

在浏览器中显示如下:

poem-with-line-break

你可以看到这首诗现在更具可读性,并且格式美观。

一些有价值的建议:不要使用 <br> 标签在块级元素(ph1h2h3div 等)之间强制使用空格。请使用 CSS 边距属性。

你可能想知道 - 由于 <br> 标签是一个元素,是否可以对其进行样式设置?

嗯,这是可能的。但是并不需要对它做什么设计,因为它所做的只是创造了几个空白。

小结

希望本教程为你提供了使用 <br> 标签所需的背景知识,以便你可以更好地排版 HTML 文本。

感谢你阅读本文。编码愉快!

原文:HTML Line Break – How to Break a Line with the HTML <br> Tag,作者:Kolade Chris