loading...

How to center elements vertically on a create-react-app project

mcrowder65 profile image Matt Crowder ・1 min read

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

Posted on by:

mcrowder65 profile

Matt Crowder

@mcrowder65

Software Engineer at Appian, previously at Walmart Labs. Co-organizer of novajavascript.com, public speaker, teacher, codementor.io/mcrowder65

Discussion

pic
Editor guide
 

The margin & the height makes huge difference 😮

 

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.