原文:Text Align in CSS – How to Align Text in Center with HTML,作者:Jessica Wilkins

有很多时候,你会需要使用 HTML 和 CSS 将一些文本居中。但什么才是最好的方法呢?

在这篇文章中,我将向你展示如何使用 CSS 中的 text-align 属性,并向你展示如何使用 CSS Flexbox 垂直对齐文本。我还将谈谈 <center> 标签,以及为什么你不应该用它来居中显示文本。

如何使用 CSS 中的 text-align 属性

当你使用标题或段落标签时,HTML 中的默认样式会将文本定位在页面的左侧。

在这个例子中,我们有一个 <h1>,它被放置在页面的左上方。

<h1 class="title">Let's learn about centering text</h1>
Screen-Shot-2022-04-24-at-11.41.12-AM

如果我们想在页面上水平居中文本,那么我们可以使用 text-align 属性。

.title {
  text-align: center;
}
Screen-Shot-2022-04-24-at-11.42.48-AM

如果你想让页面上的所有文本水平居中,那么你可以使用 body 选择器中的 text-align 属性。

在接下来的这个例子中,我们的 HTML 中还有一些文本。

<h1>freeCodeCamp is awesome</h1>
<section>
  <h2>I love learning about HTML</h2>
  <p>Here is my first paragraph</p>
</section>

<section>
  <h2>I love learning about CSS</h2>
  <p>Here is my second paragraph</p>
</section>

在没有任何样式的情况下,它目前在页面上看起来是这样的。

Screen-Shot-2022-04-24-at-12.30.14-PM

在我们的 CSS 中,我们可以定位 body 选择器并使用 text-align 属性。

body {
  text-align: center;
}
Screen-Shot-2022-04-24-at-12.29.56-PM

如何使文本水平和垂直居中

text-align 属性是用来将文本在页面上水平居中的。但我们也可以使用 CSS Flexbox来使文本垂直居中。

在这个例子中,我们的 HTML 里有一些文本:

<h2 class="title">Let's learn how to center text vertically and horizontally</h2>

<div class="flex-container">
  <p>Flexbox is cool!!!</p>
</div>

这是它目前没有任何样式的样子:

Screen-Shot-2022-04-24-at-12.35.30-PM

我们可以使用 text-align 属性将 <h2> 居中。

.title {
  text-align: center;
}
Screen-Shot-2022-04-24-at-12.42.49-PM

然后,我们可以使用 Flexbox 对 flex-container div 内的段落进行水平和垂直居中。

.flex-container {
  display: flex;

  /*this centers the text horizontally*/
  justify-content: center;

  /*this centers the text vertically*/
  align-items: center;

  height: 200px;
  color: #fff;
  font-size: 1.2rem;
  background: #00008b;
}
Screen-Shot-2022-04-24-at-12.58.57-PM

你应该使用 Center 标签吗?

在旧版本的 HTML 中,<center> 标签被用作将文本在页面上水平居中的一种方式。

<center>I am using center tags to center my text
  <p>This paragraph is also centered</p>
</center>
Screen-Shot-2022-04-24-at-12.14.09-PM

很多新的开发者仍然会使用这个标签,因为它确实能显示正确的结果。然而,<center> 标签在 HTML 4 中被废弃了,因为最佳做法是使用 CSS 的 text-align 属性来代替。

Screen-Shot-2022-04-24-at-12.16.58-PM
MDN 上的弃用警告

重要的是要记住,HTML 是用于内容的,而 CSS 是用于样式的。最好的做法是将这两个问题分开,不要将 HTML 用于样式设计。

我希望你喜欢这篇关于如何使用 HTML 和 CSS 将文本居中的文章。