F flexr.dev

Layout Recipe

Center an Image with Tailwind Flexbox

Images are inline elements, so classic centering tricks often fail. The reliable fix: put 'flex justify-center items-center' on the image's parent container, and the image centers both ways regardless of its dimensions. This works for logos in cards, avatars in list rows, and hero illustrations. If you only need horizontal centering, 'flex justify-center' alone does it — or use 'mx-auto' on the image itself with 'block'.

The playground below is pre-configured with this exact layout — tweak any control to explore, then copy the Tailwind or vanilla CSS from the exporter.

Live Preview

Current Layout:

Center an image on both axes

Images are inline elements, so old centering tricks are unreliable. The dependable fix is to make the image's parent a centering flex container: flex items-center justify-center. The image then sits dead-center regardless of its size — just give the parent a height so the vertical part has room.

Tailwind
<div class="flex items-center justify-center h-64">
  <img src="/logo.png" alt="Logo" />
</div>
Vanilla CSS
.frame {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 16rem;
}

Horizontal only: mx-auto

If you only need horizontal centering, skip flexbox entirely: make the image a block and add auto side margins with mx-auto block. This is perfect for a centered hero image or an avatar above centered text.

Tailwind
<img src="/hero.png" alt="" class="mx-auto block" />

Filling a frame with object-cover

To center and crop an image to fill a fixed box, combine a size with object-cover. It scales the image to cover the box while keeping its center in view, so the picture never stretches or distorts.

Tailwind
<img src="/photo.jpg" alt="" class="h-64 w-64 rounded-lg object-cover" />

Common mistakes

Leaving the image inline. Text-align tricks are unreliable for images; center the parent with flex instead.

No parent height. Vertical centering needs vertical space in the container.

Using object-fill. It stretches the image; reach for object-cover to crop without distortion.

Frequently asked questions

How do I center an image in Tailwind?
Put flex items-center justify-center on the image's parent container and give the parent a height; the image centers on both axes.
How do I center an image horizontally only?
Add mx-auto block to the image. Auto side margins center a block-level element horizontally.
How do I center and crop an image to a fixed size?
Use a fixed width and height plus object-cover, which scales the image to fill the box from its center without distortion.

Popular Layout Guides