DEV Community

Matt Crowder
Matt Crowder

Posted on

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

TLDR: Just add the following to public/index.html

<style>
  html, body, #root, #root>div {
    height: 100%;
    margin: 0;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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"
  }}
>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Source code available here: https://github.com/mcrowder65/centered-cra-example

Top comments (3)

Collapse
 
dance2die profile image
Sung M. Kim

The margin & the height makes huge difference 😮

Collapse
 
_juliettech profile image
juliette_chevalier

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!

Collapse
 
nickzanetti profile image
nick-zanetti

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.