DEV Community

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

Posted on

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.

Discussion (2)

Collapse
paytondev profile image
Breeana Payton Author

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