DEV Community

Cover image for How To Center A Div Within A Div
Breeana Payton
Breeana Payton

Posted on

2 1

How To Center A Div Within A Div

I don’t think I’ve met a single soul working in web development who hasn’t googled this more than once. Whether you’re new and trying to finish that first project, or like me and immediately forget everything you’ve learned once you start a project, this is just one of those concepts that takes a while to stick. Either way I won’t judge nor will I waste your time. There are a ton of ways to accomplish this task. I’ll keep it simple and show you my go-to.

Hello Flexbox 👋

Since the goal of most web pages is to make them responsive, using flexbox cuts down on a lot of the work when working on media queries.

Prerequisites

  • Make sure the height CSS property of both the body and HTML is set to 100%

  • Make sure the display CSS property of your parent container is set to flex

Now we can apply some CSS and HTML as follows:

HTML

<div id="flex-container">
    <div>
        I am centered
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

html, body {
    height: 100%:
    margin:0;
}

#flex-container {
display: flex;
height: 100vh;
background-color: #31493C;
justify-content: center;
align-items: center;
}

#flex-item {
background-color: #FCA311;
}
Enter fullscreen mode Exit fullscreen mode

The result:
Full screen centered div

And when you resize the window:
Half screen centered div

Simple. Now if you’re a beginner I want you to think about something. There is a line in this code that could give you problems if the “flex-container” isn’t the outermost container. I did this because you shouldn't copy code you don’t fully understand. Tell me which line is the potential issue in the comments below… or yell at me about it. I accept both.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
paytondev profile image
Breeana Payton

Definitely! I also like to use the negative margins approach.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay