Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Ali Pazani
To center a component horizontally and vertically in React.js, set its
display
property to flex
and its alignItems
and justifyContent
properties to center
. The components's content will be horizontally and
vertically centered.
const App = () => { return ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', }} > <h2>Some content here</h2> </div> ); }; export default App;
If you don't want to make the component full height, remove the height
property from the style
object.
We used inline styles to center a component 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.
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>Some content here</h2> </div> ); }; export default App;
Alternatively, you can center a component by writing your css in file with a
.css
extension and importing it.
.centered { display: flex; justify-content: center; align-items: center; height: 100vh; }
And here is how we would import and use the centered
class.
import './App.css'; const App = () => { return ( <div className="centered"> <h2>Some content here</h2> </div> ); }; export default App;
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', justifyContent: 'center', alignItems: '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.