CSS
CSS: How to Center a div (Horizontally and Vertically)
Centering a <div>
is one of the most common layout tasks in CSS. Depending on whether you’re aligning it horizontally, vertically, or both, there are several modern and reliable techniques to get it done.
In this blog, you’ll learn:
- ✅ How to center a
<div>
horizontally - ✅ How to center a
<div>
vertically - ✅ How to center a
<div>
both horizontally and vertically - 🧪 Real code examples using Flexbox, Grid, and other methods
- 💡 Best practices for responsive layouts
✅ 1. Center a <div>
Horizontally Using margin: auto
This is the classic and simplest way to center a block-level <div>
horizontally.
✅ HTML:
<div class="center-box">
I'm centered horizontally!
</div>
✅ CSS:
.center-box {
width: 300px;
margin: 0 auto;
}
🟢 Works well when you know the width of the div.
✅ 2. Center a <div>
Using Flexbox (Horizontally and Vertically)
Flexbox is the most modern and responsive way to center elements in both directions.
✅ HTML:
<div class="flex-container">
<div class="centered-div">I'm centered!</div>
</div>
✅ CSS:
.flex-container {
display: flex;
justify-content: center; /* Horizontal */
align-items: center; /* Vertical */
height: 100vh;
}
.centered-div {
padding: 20px;
background: #f2f2f2;
border: 1px solid #ccc;
}
🎯 Result: The inner <div>
is perfectly centered inside the container.
✅ 3. Center a <div>
Using CSS Grid
CSS Grid also provides a quick one-liner to center a <div>
.
✅ CSS:
.grid-container {
display: grid;
place-items: center;
height: 100vh;
}
✅ HTML:
<div class="grid-container">
<div class="centered-div">Grid-centered!</div>
</div>
📌 Ideal for simple layouts with one or a few centered items.
✅ 4. Center a <div>
Vertically Using position: absolute
(Legacy Method)
Though outdated, it’s still useful in some cases.
✅ CSS:
.parent {
position: relative;
height: 300px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
This method manually offsets the <div>
using transforms.
🧠 Summary Table
Goal | Best Technique |
---|---|
Horizontal centering | margin: auto |
Horizontal + vertical | Flexbox or Grid |
Legacy layout | position + transform |
Responsive layouts | Prefer Flexbox/Grid |
🏁 Final Thoughts
Centering a <div>
is easy with the right CSS tools. For most use cases, Flexbox or Grid are your best options—clean, modern, and responsive. Use margin: auto
for simpler horizontal alignment and avoid outdated hacks unless necessary.
Mastering these techniques will help you build cleaner, more professional layouts in no time.