DEV Community

Sam Wight
Sam Wight

Posted on

Centering a div with Flexbox

I saw the tweet below on my timeline today:

Here's a simple, no bullshit guide to centering content with CSS using Flexbox. Make sure to check the Flexbox CanIUse to make sure your target browsers have good support for it, otherwise this might not work.

Creating the skeleton

To start, let's write some HTML. parent-div is the element that will hold the child div that we want to center.

<html>
  <head>
    <title>Flexbox CSS Centering Example</title>
  </head>
  <body>
    <div id="parent-div">
      <div id="child-div">
        <h1>This is an example</h1>
      </div>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

If you're wanting a good place to play around with this code in the browser, I recommend using CodePen. Here's the pen with the HTML used for this post. Just type in the CSS as we go along and you'll see everything updated in real time.

Our goal will be to get the child-div post centered within the parent div, both horizontally and vertically. We'll start by adding flexbox to the parent. Before we do this though, let's add some backgrounds to each of these elements so we can see where the browser is rendering them. Ugly, I know.

#parent-div {
  background-color: red;
}

#child-div {
  background-color: black;
}
Enter fullscreen mode Exit fullscreen mode

Adding Flexbox to the parent

Making an item display using flex is simple: just use the display: flex; CSS property.

#parent-div {
  background-color: red;
  display: flex;
}
Enter fullscreen mode Exit fullscreen mode

You shouldn't notice any changes in how the element is rendering yet. Let's add some height and width to parent element, making it the height and width of the browser viewport:

#parent-div {
  background-color: red;
  display: flex;
  width: 100%;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Centering the content

Now that we have a parent element the width and height of the screen, let's center the child element horizontally and vertically inside the parent div. We'll use the justify-content and align-items CSS properties to make this happen:

#parent-div {
  background-color: red;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

And now we should see the child element centered inside the parent div!

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker

Flexbox is so amazing. It's probably the best cross-platform layout tool that just works everywhere. I learned it by completing the flexbox zombies game. Check out my article on it, it's one of my favs that I have done. I like the animated divs in it.

flexbox-zombies

waylonwalker.com/blog/flexbox-zomb...