This content originally appeared on DEV Community and was authored by A. Moreno
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 */
}
HTML
<div class="parent">
<div class="child">I'm centered!</div>
</div>
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;
}
HTML
<div class="parent">
<div class="child">I'm centered!</div>
</div>
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;
}
HTML
<div class="child">I'm centered horizontally!</div>
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%);
}
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.
This content originally appeared on DEV Community and was authored by A. Moreno

A. Moreno | Sciencx (2025-06-28T00:28:59+00:00) 3 Ways to Center a Div in CSS (That Actually Work). Retrieved from https://www.scien.cx/2025/06/28/3-ways-to-center-a-div-in-css-that-actually-work/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.