TLDR: Just add the following to public/index.html
<style>
html, body, #root, #root>div {
height: 100%;
margin: 0;
}
</style>
You've just run create-react-app my-app
, and now you edit your App.js
file to include a centered button:
import React, { Component } from "react";
class App extends Component {
render() {
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<button onClick={() => alert("hello")}>alert hello</button>
</div>
);
}
}
export default App;
But, oh no! It is only centered horizontally, and not vertically!
To look further, add a background color to your div there, like so:
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
backgroundColor: "blue"
}}
>
You will notice that the blue background does not take up the entire screen, even though this div is the only thing in the application at the moment.
In order to fix this, add the following to public/index.html
:
<style>
html, body, #root, #root>div {
height: 100%;
margin: 0;
}
</style>
Source code available here: https://github.com/mcrowder65/centered-cra-example
Top comments (3)
The margin & the height makes huge difference 😮
This just saved my life haha I've been looking for this information everywhere and hadn't stumbled upon anything that fixed my issue with Material Theme. Thank you so much!
Thanks for this guide. I had definitely been getting around this issue in an overly convoluted way and didn't think to just add that in-line style tag to the root index file.