How to center a div in React.js


Borislav Hadzhiev

Last updated: Apr 20, 2022


Check out my new book

Center a div in React.js #

To center a div in React.js, set its display property to flex and its alignItems and justifyContent properties to center. The div's content will be horizontally and vertically centered.

const App = () => { return ( <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', }} > <h2>hello world</h2> </div> ); }; export default App;

If you don't want to make the div full height, remove the height property from the style object.

We used inline styles to center a div in React.

Notice that we used two sets of curly braces when passing the style prop to the div element.

The outer set of curly braces marks an expression that is to be evaluated, and the inner set is the object of styles and values.

Note that multi-word properties are camelCased when specified as inline styles.

You can also extract the style into a variable.

const App = () => { const styles = { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', }; return ( <div style={styles}> <h2>hello world</h2> </div> ); }; export default App;

Alternatively, you can center a div by writing your css in file with a .css extension and importing it.

.centered-div { display: flex; align-items: center; justify-content: center; height: 100vh; }

And here is how we would import and use the centered-div class.

import './App.css'; const App = () => { return ( <div className="centered-div"> <h2>hello world</h2> </div> ); }; export default App;
When importing global CSS files in React, it's a best practice to import the CSS file into your index.js file.

The index.js file is the entry point of your React application, so it's always going to be ran.

On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.

A very common pattern in React is to extract commonly used styles into a component that renders its children.

function Center({children}) { return ( <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', }} > {children} </div> ); } const App = () => { return ( <Center> <h2>hello world</h2> </Center> ); }; export default App;

This example achieves the same result.

Whatever we pass between the opening and closing tags of the Center component will get centered on the page.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.