DEV Community

Cat
Cat

Posted on • Updated on

How to Center a Div with CSS in 3 Steps!

Every dev's challenge: center a div.
Nightmare mode: center it vertically AND horizontally.

Well, you don't have to fret any longer! Here's a foolproof, short way to do it. All you need are two elements: a container and your content.

Step 1: Set up your HTML.

This is very short and sweet: you just need two divs! I like to declare the class semantically so we'll call them container and content.

<div class="container">
  <div class="content">
    <p>This is some centered content</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up your container's CSS.

We'll give container a width of 100% and a height of 100vh. This ensures that your canvas is covered.

Then, we take care of what's inside by declaring display: flex, justify-content: center, and align-items: center. This ensures your content is centered.

.container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: CSS - Set up your content.

For the content itself, you're free to style this how ever you'd like. Since we don't have much content, I set the width to 300px. You can also apply it as a percentage width to keep it responsive!

.content {
  width: 300px;
}
Enter fullscreen mode Exit fullscreen mode

And that's it! That's all you need to set your content at the absolute center. Here's a codepen for your convenience to copy out of:


Thanks for reading!!

If you like my content, please give me a follow on Twitter!

Top comments (4)

Collapse
 
tobisgd profile image
TobiSGD

To add to that, align-items and justify-content have the shorthand property place-items, so you can replace them with a simple place-items: center; to get down to two lines.

Collapse
 
cat profile image
Cat

Oh, nice! I had no idea place-items existed! Thanks for the tip!

Collapse
 
julianab14 profile image
julianab14

Why can't I just use one div for it?

Collapse
 
cat profile image
Cat

It's because one div encapsulates the other. You need the surrounding div to set the stage for the content div.