I currently have a ReactJS + React Router project set up and in Chrome dev tool under elements shows:
<body>
<div class="wrapper">
<div data-reactroot>
<div>
<div class="container">Center Me</div>
</div>
</div>
</div>
</body>
with styling and none for class="wrapper"
:
.container {
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
Yet the <div class="container">Center Me</div>
is staying at the top and centered horizontally but not vertically.
I checked the size of that div and it is extremely short but takes up full width of the browser page.
What could I be doing wrong? How can I center <div class="container">Center Me</div>
? I even tried to set 100% for width and height
on a higher level, but still does not work.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
You have to use headerRight: (<View></View>) to appear at center. Save this answer.
To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
Just:
<div style={{display: 'flex', justifyContent:'center', alignItems:'center', height: '100vh'}}> <h1> I am centered </h1> </div>
or css:
.centered { height: 100vh; /* Magic here */ display: flex; justify-content: center; align-items: center; }
<div class="centered"> <h1> I am centered </h1> </div>
Here's a code example that basically recreates your page but without react. Hope this helps and shoot away if you have any questions.
html, body{ width: 100%; height: 100%; } .wrapper{ width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } .container { height: 300px; width: 300px; background: black; color: white; display: flex; align-items: center; justify-content: center; }
<html> <body> <div class="wrapper"> <div data-reactroot> <div class="container"> <div> <!-- Anything below this line will be centered --> <div>Hello World!</div> <div>Center Me</div> <!-- Anything above this line will be centered --> </div> </div> </div> </div> </body> <html>
I just wrap my div
with Grid
and added justify="center" attr.
:
<Grid container spacing={2} justify="center"></Grid>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With