Can someone help me figure out why centering an image in CSS isn’t working?

I’m having trouble centering an image in CSS. No matter what I try, it just won’t center unless I use padding. I’ve tried using Flexbox with justify-content and align-items, but it still doesn’t work. I’m not sure what I’m doing wrong.

Here’s the code I have so far:

img {
  padding: inherit;
  margin: auto;
  text-align: center;
}

Can someone help me figure out why this isn’t working?

Hey @anjuyadav.1398,

It seems like you might be missing some key properties. If you’re trying to use Flexbox and it’s not working, the issue is likely with the parent container. For centering an image in CSS using Flexbox, the parent container must have display: flex. Here’s how you can fix it:

.parent {
  display: flex;
  justify-content: center; /* Centers the content horizontally */
  align-items: center;    /* Centers the content vertically */
  height: 100vh;          /* Ensures the parent container has enough height for vertical centering */
}

This setup will center your image both horizontally and vertically. If it’s still not working, check the following:

  1. Ensure your image is a direct child of the .parent container.
  2. Verify there aren’t any conflicting styles (like margins, paddings, or positioning) affecting the image or its container.

Let me know if this helps or if you’re still having trouble!

There is also a simple fix @anjuyadav.1398

If you want a simpler fix, you can use text-align: center in the parent container and make your image a block-level element. This is a classic trick for centering an image in CSS horizontally:

.parent {
  text-align: center; /* Centers inline elements, including images */
}
img {
  display: block; /* Makes the image behave like a block for better control */
  margin: auto;   /* Helps keep things centered */
}

This is a straightforward solution if you only need horizontal centering. It’s great when you don’t need to mess with Flexbox or Grid.

Learn the difference between CSS Grid vs Flexbox and see which to choose and when to make these layouts work well.

Adding to the insights shared by @raimavaswani and @tim-khorev (which are excellent approaches), I’d like to suggest an alternative. If Flexbox isn’t working as expected or you’re looking for a modern and simple solution, CSS Grid is a fantastic option for centering an image in CSS. Here’s how you can achieve it:

.parent {
  display: grid;
  place-items: center; /* Centers both horizontally and vertically */
  height: 100vh;       /* Ensures enough height for vertical centering */
}

The place-items: center property in CSS Grid is a game-changer—it centers elements in both directions with minimal effort. Just ensure the parent container wraps around your image, and you’re good to go! It’s clean, effective, and incredibly easy to implement.

Give it a try and see how it works for your layout!