How to Center a Div with CSS in 3 Steps!

Cat - Jan 31 '22 - - Dev Community

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player