React – Center a component horizontally and vertically

0
10

In this tutorial, we are going to learn about how to center a component horizontally and vertically in React with the help of examples.

Consider, we have the following component in our react app:

import React from 'react';

function Home()
    return (
        <div className="center">
          <h1>Home Component</h1>
        </div>
    )


export default Home;

To center a component horizontally and vertically in React, add the display:flex, justify-content: center and align-items: center to the react component CSS class.

‘justify-content: center’ centers the image horizontally.

‘align-items: center’ centers the image vertically.

Here is an example:

import React from 'react';

function Home()
    return (
        <div className="center">
           <h1>Home Component</h1>
        </div>
    )


export default Home;
.center
    display: flex;
    justify-content: center;
    align-items: center;

or we can add it inline using the style object in React.

import React from 'react';

function Home()
    return (
        <div style=
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
        >
           <h1>Home Component</h1>
        </div>
    )


export default Home;

Centering using absolute position

We can use the absolute positioning in react.js to center the component horizontally and vertically.

Here is an example:

import React from 'react';

function Home()
    return (
        <div style=
               position: 'absolute',
               left: '50%',
               top: '50%',
               transform: 'translate(-50%, -50%)'
        >
          Home Component
        </div>
    )


export default Home;
  1. Here we added position:absolute to the component div element, so the element breaks out of the normal document flow and is positioned to its relative parent (eg: body or parent component).

  2. The left:50% moves the element 50% right from its position.

  3. The top:50% moves the element 50% down from its position.

  4. The translate(-50%, -50%) moves the element 50% up, 50% left of its position.

Creating the center component

We can also create a reusable center component in React, so we can reuse it in our app instead of adding the styles every time to the component.

Example:

import React from 'react';

function Center(props)
    return (
        <div style=
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
        >
           props.children
        </div>
    )


export default Center;

Using the Center component:

import React from 'react';
import Center from './center.js'

function Home()
    return (
        <div>
           <Center>
             <h1>Home Component</h1>
           </Center>
        </div>
    )


export default Home;

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here