CSS: How to Center an Image in a div

Centering an image within a <div> is a common design need in web development. Whether you’re working on a gallery, a hero section, or a product display, placing an image neatly in the center enhances visual balance and improves user experience.

In this guide, you’ll learn multiple methods to center an image horizontally, vertically, or both inside a <div> using CSS.


🎯 Method 1: Center Image Horizontally Using text-align

This method is quick and works well for inline elements like <img>.

✅ HTML:

<div class="image-container">
  <img src="image.jpg" alt="Example Image">
</div>

✅ CSS:

.image-container {
  text-align: center;
}

Result: The image will be horizontally centered within the container.


🎯 Method 2: Center Using margin: auto

Set the image to display: block and apply automatic horizontal margins.

✅ CSS:

img {
  display: block;
  margin: 0 auto;
}

Result: The image centers itself horizontally, without affecting other elements.


🎯 Method 3: Center Image Vertically and Horizontally Using Flexbox

For both vertical and horizontal centering, Flexbox is ideal.

✅ HTML:

<div class="flex-container">
  <img src="image.jpg" alt="Centered Image">
</div>

✅ CSS:

.flex-container {
  display: flex;
  justify-content: center;  /* horizontal */
  align-items: center;      /* vertical */
  height: 300px;            /* or any height you need */
}

Result: The image is centered perfectly in both directions inside the div.


🎯 Method 4: Use Grid for Simple Centering

CSS Grid makes centering extremely easy with just one line.

✅ CSS:

.grid-container {
  display: grid;
  place-items: center;
  height: 300px;
}

Result: The image is centered both horizontally and vertically using Grid layout.


📝 Bonus: Tailwind CSS Example

If you’re using Tailwind CSS:

<div class="flex justify-center items-center h-64">
  <img src="image.jpg" alt="Tailwind Image">
</div>

🔍 When to Use Which Method?

Use CaseRecommended Method
Only horizontal centeringtext-align or margin: auto
Full vertical + horizontal centeringFlexbox or CSS Grid
Responsive or modern layoutsFlexbox / Grid
Quick styling for inline imagestext-align: center

Conclusion

Centering an image in a <div> using CSS can be done in several effective ways. For basic layouts, text-align or margin: auto works well. For responsive and vertically-centered designs, Flexbox or Grid is the best choice.

Mastering these techniques ensures your images are perfectly aligned no matter the context — improving both usability and aesthetics.

Sharing Is Caring:

Leave a Comment