Last updated: Apr 6, 2024
Reading time·3 min
To center a div
or a component horizontally and vertically, 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>bobbyhadz.com</h2> </div> ); }; export default App;
If you don't want to make the div full height,
remove the height
property from the style
object.
This is what the component looks like with the height: '100vh'
line removed.
We used inline styles to center a div in React.
div
of the component and not on a nested div
element.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.
If you need to get the height and width of an element, click on the following article.
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>bobbyhadz.com</h2> </div> ); }; export default App;
div
or component using an external CSS file in ReactAlternatively, you can center a div by writing your CSS in a file with a .css
extension and importing it.
.centered-div { display: flex; align-items: center; justify-content: center; height: 100vh; }
Here is how we would import and use the centered-div
class.
import './App.css'; const App = () => { return ( <div className="centered-div"> <h2>bobbyhadz.com</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 run.
On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.
Center
component to center a div or other componentsA 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>bobbyhadz.com</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.
The h2
tag we passed between the opening and closing tags of the Center
element gets passed as the children
prop to the Center
component.
The Center
component takes the supplied children
prop and centers the
elements horizontally and vertically.