一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第21天,点击查看活动详情。
在本文中,我将向你展示如何text-align
在 CSS 中使用该属性,并展示如何使用 CSS Flexbox 垂直对齐文本。我还将讨论<center>
标签以及为什么不应该使用它来居中文本。
如何text-align
在 CSS 中使用属性
当你使用标题或段落标签时,HTML 中的默认样式会将文本放置在页面的左侧。
在这个例子中,我们有一个<h1>
放在页面左上角的。
<h1 class="title">Let's learn about centering text</h1>
如果我们想在页面上水平居中文本,那么我们可以使用该text-align
属性。
.title {
text-align: center;
}
如果你想将页面上的所有文本水平居中,则可以使用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>
没有任何样式,它目前在页面上看起来像这样。
在我们的 CSS 中,我们可以定位body
选择器并使用该text-align
属性。
body {
text-align: center;
}
如何水平和垂直居中文本
该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>
这是它目前看起来没有任何样式的样子。
我们可以<h2>
使用text-align
属性居中。
.title {
text-align: center;
}
flex-container
然后,我们可以使用 Flexbox在 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;
}
你应该使用中心标签吗?
在旧版本的 HTML 中,<center>
标签被用作在页面上水平居中文本的一种方式。
<center>I am using center tags to center my text
<p>This paragraph is also centered</p>
</center>
许多新开发人员仍会使用此标签,因为它确实显示了正确的结果。但是,该<center>
标记在 HTML 4 中已被弃用,因为最佳实践是改用 CSStext-align
属性。
这是来自MDN 文档的弃用警告
重要的是要记住 HTML 用于内容,而 CSS 用于样式。最好的做法是将这两个问题分开,不要将 HTML 用于样式目的。
我希望你喜欢这篇关于如何使用 HTML 和 CSS 使文本居中的文章。