React 中的文本居中
我们将使用不同的方式来介绍如何在 React 中使文本居中。
在 React 中水平居中文本
在页面上工作时,我们必须将文本向右、向左或居中对齐。使用 index.tsx
文件中 style
内的 textAlign
属性在 React 中对齐文本非常容易。
# react
<div>
<h2 style={{textAlign: "center"}}>Inline Styling</h2>
<p style={{textAlign: "center"}}>
This text is aligned center by adding inline css
</p>
</div>
输出:
使多个元素的文本居中的另一种方法是在 style.css
文件中添加 css 代码。
让我们使用 h2
标签创建一个标题,使用 p
标签创建一个段落。然后,为这两个元素添加一个 textCenter
类。
# react
<h2 className="centerText">Using Style.css</h2>
<p className="centerText">This text is aligned center by adding css in style.css file</p>
让我们在 style.css
文件中编写 CSS 代码。
# react
.centerText{
text-align: center;
}
输出:
在 React 中垂直居中文本
有时我们必须垂直对齐文本以使其看起来更好,并使我们的 UI 更好。在 React 中有两种简单的方法可以使文本垂直居中对齐。
让我们创建一个标题并将其垂直居中对齐。
# react
<h2 style={{ flex: 1, justifyContent: 'center', alignItems:"center", lineHeight:"100px"}}>Aligning Vertically</h2>
在上面的代码中,我们添加了 lineHeight: '100px'
以显示文本是垂直居中
。
输出:
我们可以看到我们已经成功地将标题垂直居中。
垂直居中多个元素的另一种方法是在 style.css
文件中添加 CSS 代码并为元素分配一个类。
因此,首先,我们将创建一个标题和一个段落,并将 verticalCenter
类分配给这两个元素。
# react
<h2 className="verticalCenter">Using Style.css</h2>
<p className="verticalCenter">This text is vertically aligned center by adding css in style.css file</p>
让我们在 style.css
文件中添加 CSS 代码。
# react
.verticalCenter{
flex: 1;
justify-content: center;
line-height: 100px;
}
输出:
我们可以看到我们已经成功地将两个元素垂直居中。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。