CSS
CSS: How to Center an Image in a div
Centering an image inside a <div>
is one of the most common layout tasks in web design. Whether you’re trying to align an image horizontally, vertically, or both, CSS gives you multiple ways to do it—each suited for a different use case.
In this blog post, you’ll learn:
- ✅ How to center an image horizontally
- ✅ How to center an image vertically
- ✅ How to center an image both horizontally and vertically
- 🧪 Real-world code examples for each method
✅ 1. Center Image Horizontally Using text-align: center
If your image is inline (which <img>
is by default), the easiest method is to use text-align: center
on the parent <div>
.
✅ HTML:
<div class="container">
<img src="image.jpg" alt="Centered Image">
</div>
✅ CSS:
.container {
text-align: center;
}
✅ Result: The image is centered horizontally inside the div.
✅ 2. Center Image Horizontally Using margin: auto
If you want more control or your image is set to display: block
, you can center it using margin: auto
.
✅ CSS:
img {
display: block;
margin: 0 auto;
}
📌 Useful when you don’t want to apply styles to the container.
✅ 3. Center Image Vertically Using Flexbox
To center vertically, you’ll need to use modern layout tools like Flexbox.
✅ HTML:
<div class="flex-center">
<img src="image.jpg" alt="Centered Image">
</div>
✅ CSS:
.flex-center {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
height: 300px; /* required to center vertically */
}
✅ Result: The image is centered both horizontally and vertically inside the <div>
.
✅ 4. Center Image Using CSS Grid
CSS Grid offers a clean one-liner approach.
✅ CSS:
.grid-center {
display: grid;
place-items: center;
height: 300px;
}
✅ HTML:
<div class="grid-center">
<img src="image.jpg" alt="Centered Image">
</div>
✅ Result: Perfect center, no fuss.
🧠 Summary Table
Goal | CSS Technique | Best For |
---|---|---|
Horizontal only | text-align: center | Inline elements like <img> |
Horizontal only (block) | margin: 0 auto | When image is display: block |
Vertical & horizontal | Flexbox | Most responsive solution |
Vertical & horizontal | Grid | Clean one-line centering |
🔚 Final Thoughts
Centering images in a div is easy once you choose the right tool for your layout:
- Use
text-align
for quick fixes - Use
margin: auto
for block images - Use Flexbox or Grid for pixel-perfect modern design