DEV Community

Cover image for 3 Ways to Center a Div in CSS (That Actually Work)
A. Moreno
A. Moreno

Posted on

3 Ways to Center a Div in CSS (That Actually Work)

Let’s be honest — centering a div shouldn’t be this complicated. But if you’ve ever Googled it, you’ve probably run into dozens of answers, and not all of them are reliable.

Here are 3 modern, reliable ways to center a div — both horizontally and vertically — that I use all the time in real-world projects.


1. Using Flexbox

CSS

.parent {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
  height: 100vh; /* or any height you need */
}
Enter fullscreen mode Exit fullscreen mode

HTML

<div class="parent">
  <div class="child">I'm centered!</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Why it works: Flexbox is made for alignment. This combo centers the child perfectly inside the parent.


2. Using Grid

CSS

.parent {
  display: grid;
  place-items: center;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

HTML

<div class="parent">
  <div class="child">I'm centered!</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Why it works: place-items: center is shorthand for centering both horizontally and vertically. Clean and powerful.


3. Margin Auto (Horizontal Only)

CSS

.child {
  width: 200px;
  margin: 0 auto;
}
Enter fullscreen mode Exit fullscreen mode

HTML

<div class="child">I'm centered horizontally!</div>
Enter fullscreen mode Exit fullscreen mode

Why it works: When you set a fixed width and apply margin: auto, the element centers itself in its container — but only horizontally.


Bonus: Absolute Positioning (Old but Gold)

CSS

.parent {
  position: relative;
  height: 100vh;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode

When to use it: If you're stuck with older layout styles and can't use Flexbox or Grid — this still gets the job done.


Wrap-Up

If you're building modern layouts, Flexbox and Grid are your best tools. You’ll see them everywhere — from simple forms to full page layouts.

Stop fighting CSS. Use one of these, and center with confidence.

Top comments (2)

Collapse
 
om_shree_0709 profile image
Om Shree

good work

Collapse
 
mileswk profile image
MilesWK

If you also want to get fancy with it, you can use Tailwind CSS, and add a class to make it work.