How to Center Text in React

Rana Hasnain Khan Feb 02, 2024
  1. Center Text Horizontally in React
  2. Center Text Vertically in React
How to Center Text in React

We will use different ways to introduce how to center text in React.

Center Text Horizontally in React

When working on a page, we have to align text towards, right, left, or center. It is very easy to align text in React using textAlign property inside style in index.tsx file.

# react
<div>
        <h2 style={{textAlign: "center"}}>Inline Styling</h2>
        <p style={{textAlign: "center"}}>
        This text is aligned center by adding inline css
        </p>
      </div>

Output:

center text by inline style in react

Another way to center the text for multiple elements is by adding the css code in the style.css file.

Let’s create a heading using the h2 tag and a paragraph using the p tag. Then, add a class of textCenter to both elements.

# react
<h2 className="centerText">Using Style.css</h2>
        <p className="centerText">This text is aligned center by adding css in style.css file</p>

Let’s write CSS code in the style.css file.

# react
.centerText{
  text-align: center;
}

Output:

center text by using style file

Center Text Vertically in React

Sometimes we have to align text vertically to make it look better and make our UI better. There are two simple ways to align text vertically center in React.

Let’s create a heading and align it vertically center.

# react
<h2 style={{ flex: 1, justifyContent: 'center', alignItems:"center", lineHeight:"100px"}}>Aligning Vertically</h2>

In the above code, we have added lineHeight: '100px' to show that the text is vertically centered.

Output:

vertically aligning text in react

We can see that we have successfully vertically centered our heading.

Another way to center multiple elements vertically is by adding CSS code in the style.css file and assigning a class to the elements.

So, first of all, we will create one heading and a paragraph and assign the verticalCenter class to both elements.

# 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>

Let’s add CSS code in the style.css file.

# react
.verticalCenter{
  flex: 1;
  justify-content: center;
  line-height: 100px; 
}

Output:

vertically aligned heading using style file

vertically aligned paragraph using style file

We can see that we have successfully vertically centered both elements.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn