MEDIA GUIDES / Image Effects

How to Center an Image in HTML and CSS

image align center html css

Key takeaways:

  • An <img> is an inline element by default, so margin: 0 auto does nothing until you also set display: block on the image.
  • Vertical centering needs spare height: Flexbox (align-items: center) and Grid (place-items: center) can only move an image down when the parent is taller than the image.
  • Absolute positioning with top: 50%, left: 50% and transform: translate(-50%, -50%) centers an image of any size on both axes, which suits overlays such as an icon over a thumbnail.
  • CSS centers the image box, not the subject inside the photo; for that, crop with object-position in CSS or with a Cloudinary URL parameter such as g_auto.

A well-positioned image can make a webpage feel polished, balanced, and easier to navigate. However, centering images with HTML and CSS can require different techniques depending on the layout, image dimensions, and whether the image appears within a block, flex, or grid container.

Manual styling works well for individual elements, but larger media libraries often require a more consistent approach. By combining responsive design with automated image transformations through Cloudinary, you can standardize image sizing, alignment, and delivery across your website.

In this article:

HTML Center Image Methods Compared

Method CSS to add Centers horizontally Centers vertically Use it for
Auto margins On the img: display: block; margin: 0 auto; Yes No One image on its own line, such as a logo or an article figure
text-align On the parent: text-align: center; Yes No An image inside a centered column of text (the text is centered too)
Flexbox On the parent: display: flex; justify-content: center; align-items: center; Yes Yes, when the parent has a height Images in a row with other items, cards, hero sections
Grid On the parent: display: grid; place-items: center; Yes Yes, when the parent has a height The shortest two-axis rule; gallery cells
Absolute position and transform Parent: position: relative; image: position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); Yes Yes Overlays that sit on top of other content
<center> element or align attribute None (obsolete HTML) <center> yes, align no No Nothing new: both are obsolete in the HTML standard

Block vs. Inline HTML elements

Most image-centering problems come from one detail: an <img> is an inline element, so rules written for block boxes, such as auto margins, have no effect on it until you change how it is displayed. The essential thing to remember when working with HTML and CSS is the behavior of block and inline HTML elements in a layout flow.

Block Elements

HTML block elements are laid out one after the other, either vertically or horizontally, depending on the writing mode used. In other words, block-level elements typically start on a new line and occupy the full width available to them in a given layout or container. Block elements include:

  • <div>
  • <p>
  • <h1> - <h6&gt;
  • <ul>, <ol>, and <li>
  • <table>
  • <form>

image align center html css

Inline Elements

Inline elements display one after the other in the direction that sentences run in that particular writing mode. These don’t start on a new line and only take up as much width as their content requires.

Images are a special case. <img> is a replaced element whose default display is inline, while its size comes from the image file itself, as if it were inline-block. That is why text-align on the parent moves an image, and why auto margins only work after you set display: block.

image align center html css

How to Center an Image in CSS With margin: 0 auto

The most common way to center an image horizontally is to make it a block and give it automatic left and right margins. The browser splits the leftover width of the container equally between the two margins, which puts the image in the middle.

<style>
  .centered {
    display: block;
    margin: 0 auto;
    max-width: 100%;
    height: auto;
  }
</style>

<img class="centered" src="photo.jpg" alt="Product photo" width="600" height="400" />
  • display: block is required because the CSS specification turns auto left and right margins on an inline image into 0, so margin: 0 auto on its own does nothing.
  • In margin: 0 auto, the 0 sets the top and bottom margins and auto applies to the left and right ones.
  • max-width: 100% keeps a large image inside a narrow screen, and height: auto keeps its proportions when it shrinks.

Auto margins can only share space that exists. If the image is as wide as its container, there is nothing left to split, so the image cannot move; give it a smaller width first, for example width: 50%. The logical property margin-inline: auto does the same job as setting margin-left and margin-right to auto in horizontal text.

Center Images Using text-align

When you’re working with a very basic layout, the simplest way to align an image in the center of its parent container is to use the text-align: center CSS declaration on the parent element. Below is an example code showing this in action:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 100%;
        text-align: center;
      }
      .image img {
        width: 50%;
        height: auto;
      }
    </style>
  </head>
  <body>
    <section class="container">
      <div class="heading-wrapper">
        <div class="heading">
          <h2 class="heading-text">Centering images with HTML and CSS</h2>
        </div>
      </div>
      <div class="image-wrapper">
        <div class="image">
          <img
            width="2070"
            height="1380"
            src="https://images.unsplash.com/photo-1714745455353-f47a2e2b5647?q=80&w=2070&auto=format&fit=crop"
            alt="A man in a black hat standing in the middle of the street"
          />
        </div>
      </div>
      <div class="text-wrapper">
        <div class="text">
          <p class="text-1">
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis
          alias ratione repudiandae adipisci quaerat, e consequuntur maxime
          veniam et corrupti aliquam sunt nulla! Error iste velit minima a odio
          omnis? Repudiandae.
          </p>
        </div>
      </div>
    </section>
  </body>
</html>

Here’s the output:

image align center html css

Put text-align: center on the parent, not on the image. The property applies to block containers and centers the inline content inside them, so set on the <img> itself it has no effect. It also centers every line of text in that container, which is why it suits simple, centered layouts best.

Use the image file’s real size in pixels for those attributes, written as whole numbers without units, as MDN specifies. The browser uses them to work out the aspect ratio and reserve space before the image loads; the displayed size, such as 50%, belongs in CSS together with height: auto.

Center images with Flexbox

In CSS, Flexbox is a one-dimensional layout method for arranging items in rows or columns. Using Flexbox, we can easily control whether to align an image vertically or horizontally. The following are the CSS properties and declarations we’ll be looking at in this section.

  • display: flex: This creates a flex container, which enables a Flexbox layout.
  • justify-content: This controls the alignment of all items along the main axis of a flex container.
  • align-items: This specifies how flex items are aligned along the cross-axis of the flex container.
  • flex-direction: This gives the direction in which flex items are placed within the flex container. It allows us to arrange items horizontally (flex-direction: row) or vertically (flex-direction: column) or in reverse for either direction.

Center Images Horizontally with Flexbox

By default, the display: flex declaration aligns flexbox items in a horizontal plane (row), so we don’t have to use the flex-direction: row declaration here. Below’s the code from before, modified to show how this works:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .container > div {
        flex: 200px;
        margin-inline: 15px;
      }
      .image {
        width: 100%;
        height: auto;
      }
    </style>
  </head>
  <body>
    <section class="container">
      <div class="heading-wrapper">
        <div class="heading">
          <h2 class="heading-text">Centering images with HTML and CSS</h2>
        </div>
      </div>
      <div class="image-wrapper">
          <img
            class="image"
            width="2070"
            height="1380"
            src="https://images.unsplash.com/photo-1714745455353-f47a2e2b5647?q=80&w=2070&auto=format&fit=crop"
            alt="A man in a black hat standing in the middle of the street"
          />
      </div>
      <div class="text-wrapper">
        <div class="text">
          <p class="text-1">
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis
          alias ratione repudiandae adipisci quaerat, e consequuntur maxime
          veniam et corrupti aliquam sunt nulla! Error iste velit minima a odio
          omnis? Repudiandae.
          </p>
        </div>
      </div>
    </section>
  </body>
</html>

In the above code, the flex: 200px is shorthand for flex: 1 1 200px: each of the three flex items starts from a 200px width and then grows or shrinks so the three share the row equally. Because the items fill the row, justify-content: center has no free space to distribute; the image lands in the middle because it is the middle item, and align-items: center lines the heading, image and text up on their vertical midpoints. Feel free to change the 200px value for your own layout.

Here’s the output:

image align center html css

.image-wrapper {
  display: flex;
  justify-content: center;
}

.image-wrapper img {
  max-width: 100%;
  height: auto;
}

A flex item does not grow by default (its initial flex value is 0 1 auto), so the image keeps its own width and leaves free space on the row, which justify-content: center splits evenly on both sides. The max-width rule stops a large image from overflowing a narrow container.

Centering Images Vertically with Flexbox

Vertical centering needs two things: spare height in the container and an alignment rule on the vertical axis. In a row flex container, the default, justify-content works horizontally and align-items works vertically, so setting both to center on a box with a fixed height puts the image in the middle of it:

<style>
  .image-box {
    display: flex;
    justify-content: center; /* horizontal */
    align-items: center;     /* vertical */
    height: 400px;
  }
  .image-box img {
    max-width: 100%;
    height: auto;
  }
</style>

<div class="image-box">
  <img src="photo.jpg" alt="Product photo" width="300" height="200" />
</div>

Here’s the result:

image align center html css

Without the height, the box is only as tall as the image and there is nothing to center vertically. The same thing explains why flex-direction: column with justify-content: center often seems to do nothing: in a column the axes swap and justify-content works vertically, but a container with an automatic height still has no free space to share. MDN’s centering recipe sets a height on the container for this reason. Use min-height instead of height if the content might grow taller than the box.

Center Images with CSS Grid

A grid is a two-dimensional layout with a set of intersecting horizontal and vertical lines defining columns and rows. It provides precise control over the placement and alignment of elements within the grid, making it a great tool for creating complex and responsive layouts.

Center Images Horizontally with a Grid

To center an image horizontally with a CSS grid, change the code from before to the following:

<style>
.container {
width: 100%;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
justify-content: center;
}
</style>

Here’s how the code works:

  • display: grid: This sets up the container as a grid container. This means that its direct children will become grid items, and the container itself will behave like a grid.
  • grid-template-columns: This defines the number and size of the columns in the grid. In this case, grid-template-columns: 1fr 1fr 1fr; creates three equal-width columns by dividing the available space into three equal parts (each 1fr representing one fraction of the available space).
  • align-item: Center lines each item up on the vertical middle of its row, so the heading and the text sit level with the middle of the image. The justify-content: center line has no visible effect in this example: the three 1fr columns take all the leftover space, so there is none left to distribute, and the image is centered because it sits in the middle column.

And here’s the output:

image align center html css

Note: The image is set to a width of 100% to fill up the fraction of space in the grid column.

Center Images Vertically with Grid

To center an image vertically with a CSS grid, change the code to the following:

<style>
.container {
width: 100%;
display: grid;
place-items: center;
}

.image-wrapper {
display: grid;
place-items: center;
}
</style>

image align center html css

Note: The image is set to a width of 50% for this example.

place-items: center is shorthand for align-items: center plus justify-items: center, so each grid item is centered on both axes inside its cell. The min-height on .image-wrapper gives that cell spare height; without it, the cell is exactly as tall as the image and nothing moves vertically. Flexbox suits a single row or column of items, while Grid lays out rows and columns at once, which makes it the better fit for photo galleries where every cell should center its image.

How to Center an Image With position and transform

Absolute positioning centers an image on both axes inside a parent of any size, even when you don’t know the image’s dimensions. Set the parent to position: relative, move the image’s top-left corner to the middle with top: 50% and left: 50%, then pull it back by half its own size with transform: translate(-50%, -50%).

<style>
  .image-frame {
    position: relative;
    height: 400px;
  }
  .image-frame img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-width: 100%;
    height: auto;
  }
</style>

<div class="image-frame">
  <img src="photo.jpg" alt="Product photo" width="300" height="200" />
</div>

The two sets of percentages measure different things. top: 50% and left: 50% are measured against the containing block, which is the nearest positioned ancestor, so .image-frame needs position: relative. The percentages in translate() are measured against the image’s own box, which is what makes the method work for images of any size. The parent also needs a height, because an absolutely positioned image is removed from the normal flow and adds no height of its own.

Use this method for overlays, such as a play icon over a video thumbnail or a logo on top of a hero banner. For ordinary page layout, Flexbox or Grid is simpler because the image stays in the normal flow.

Old HTML Methods to Avoid: <center> and align

Don’t use the <center> element or the align attribute on <img> in new code. The HTML standard lists <center> among the elements that are entirely obsolete and must not be used by authors, and it lists align on img as an obsolete attribute. Browsers still display old pages that use them, but they mix layout into your markup and fail HTML validation.

<!-- Obsolete: do not use -->
<center><img src="photo.jpg" alt="Product photo" /></center>
<img src="photo.jpg" alt="Product photo" align="middle" />

<!-- Use CSS instead -->
<img src="photo.jpg" alt="Product photo" style="display: block; margin: 0 auto;" />

The align attribute never centered an image horizontally. Its values are top, middle and bottom, which correspond to vertical-align, and left and right, which correspond to float. So align=”middle” lines the image up vertically with the text next to it, which is why it appears to do nothing on an image that sits on its own line.

How to Center the Subject Inside an Image

Every method above moves the image box. When the real problem is that the subject sits off-center in the photo, or the photo has the wrong shape for its slot, you need to change which part of the picture shows. CSS can do that when the page is displayed; an image service can do it when it creates the file.

Crop the Visible Area With object-fit and object-position

object-fit: cover fills a fixed-size box without distorting the image, clipping whatever does not fit. object-position then decides which part stays visible. Its initial value is 50% 50%, so the crop is centered unless you move it:

.thumbnail {
  width: 300px;
  height: 300px;
  object-fit: cover;
  object-position: 50% 30%; /* keep the upper middle in view */
}

For a CSS background image, background-position: center centers the image in its box; the default is the top-left corner (0% 0%). The limit of both is that you choose the focus point by hand for each image, and the browser still downloads the full file before clipping it.

Center the Subject Automatically With Cloudinary

Cloudinary crops and pads images through parameters in the delivery URL, so one uploaded original can fill slots of any shape. By default a crop keeps the center of the image. Adding automatic gravity, g_auto, tells Cloudinary to use AI to find the most visually important area and keep it in the crop instead:

Default center crop:
https://res.cloudinary.com/demo/image/upload/c_fill,g_center,h_300,w_200/basketball_in_net.jpg

Automatic gravity:
https://res.cloudinary.com/demo/image/upload/c_fill,g_auto,h_300,w_200/basketball_in_net.jpg

Both URLs return a 200 x 300 image cut from the same 1000 x 636 original with c_fill, which produces the exact size requested without distortion. Adding the fl_getinfo flag returns the crop data as JSON: the center crop takes a window that starts 288 pixels from the left edge, while g_auto starts it at 189 pixels, about 100 pixels to the left, toward the region its analysis picked. For portraits, g_face keeps the largest face in the crop and g_faces keeps all of them.

When the whole image has to stay visible, pad it instead of cropping. c_pad resizes the image to fit inside the requested box while keeping its aspect ratio and centers it by default, and b_auto fills the empty space with a color taken from the image itself:

https://res.cloudinary.com/demo/image/upload/b_auto:predominant,c_pad,h_150,w_150/sheep.jpg

Here the 800 x 500 original is scaled to 150 x 94 and placed in the middle of a 150 x 150 square, so it drops into a square product grid already centered. Put either URL in a normal <img> tag with matching width and height attributes, and center the tag with any of the CSS methods above.

Unlock the full potential of your digital content with Cloudinary’s advanced editing and optimization tools. Sign up for free today.

Frequently Asked Questions

How to align an image in the center in HTML without CSS?

There is no current HTML-only way. The <center> element and the align attribute that old tutorials use are obsolete in the HTML standard, and align=”middle” only aligns an image vertically with text. If you cannot edit a stylesheet, an inline style attribute still works, for example <img src=”photo.jpg” alt=”Product photo” style=”display: block; margin: 0 auto;”>, although that is still CSS, written inside the tag.

How to place an image in the center of a div?

Make the div a flex container with justify-content: center for the horizontal axis and align-items: center for the vertical axis, and give the div a height so there is room to center in. display: grid with place-items: center does the same in one declaration. If you only need horizontal centering, display: block and margin: 0 auto on the image is enough.

How do I align an image with text in HTML?

For a small image inside a line of text, such as an icon, set vertical-align: middle on the <img>; MDN defines middle as aligning the middle of the element with the baseline plus half the x-height of the parent, roughly the middle of the lowercase letters. To place an image and a paragraph side by side, wrap them in a flex container with align-items: center. To let text wrap around an image, use float: left or float: right, which is what the old align=”left” and align=”right” values did.

How to center an object in HTML?

The same rules work for any element, not only images. Inline content such as text, links and images is centered with text-align: center on its parent. A block element such as a div is centered horizontally with margin: 0 auto once it is narrower than its container, and any element can be centered on both axes by making its parent a flex or grid container.

QUICK TIPS
Jen Looper
Cloudinary Logo Jen Looper

In my experience, here are tips that can help you better center images using HTML and CSS:

  1. Use inline-block for single images in inline text flows
    If you need to center a single image within a paragraph or in-line text, consider using display: inline-block on the <img> element and wrapping it in a parent container with text-align: center. This approach prevents breaking the inline text flow, keeping the surrounding content consistent.
  2. Leverage object-fit for responsive scaling
    Use the object-fit property to maintain aspect ratios of centered images when they need to be resized dynamically. For example, object-fit: cover ensures that the image scales to fill the container without distortion while still being centered.
  3. Use vertical-align for inline elements
    When dealing with inline images (e.g., <img> inside a text block), apply vertical-align: middle to the image. This vertically centers it with respect to the surrounding text without extra positioning or layout rules.
  4. Implement CSS transform for pixel-perfect centering
    To center an image precisely, especially when using absolute positioning, apply transform: translate(-50%, -50%); along with top: 50%; left: 50%;. This technique ensures the image is centered perfectly even when dimensions change.
  5. Combine margin: auto with width and height constraints
    When using margin: auto to center an image, make sure to set both width and height of the image explicitly. Otherwise, margin: auto won’t be applied properly, especially for images without a defined size or when inside a constrained container.
  6. Use Flexbox’s order property for visual reordering
    When using Flexbox, use the order property to change the visual placement of images in a responsive layout without altering the HTML structure. This is useful when the visual hierarchy needs to change for different screen sizes (e.g., mobile vs. desktop).
  7. Create scrollable image galleries with CSS Grid
    Combine CSS Grid’s grid-template-rows and grid-auto-rows properties to create dynamic, scrollable galleries where images can be centered both horizontally and vertically. This approach is ideal for creating masonry-style layouts that require both alignment and responsive behavior.
  8. Account for aspect ratio with CSS Grid’s aspect-ratio
    Use the CSS aspect-ratio property to control the ratio of the grid cells when centering images, ensuring they maintain visual consistency. For example, set aspect-ratio: 16 / 9; on the image container to control the aspect ratio, making complex layouts easier to maintain.
  9. Use pseudo-elements for placeholder centering
    When centering an image with uncertain load times (e.g., a high-resolution image from an external source), use CSS pseudo-elements (::before or ::after) to display a centered placeholder until the image loads. This prevents content shifting and ensures the layout looks centered even before the image is visible.
  10. Avoid text alignment pitfalls with RTL languages
    When using text-align: center to center images, be mindful of right-to-left (RTL) languages, as text alignment rules may affect the visual placement unexpectedly. Use logical properties like margin-inline: auto; for a more consistent centering approach across different language directions.

Implementing these strategies will give you more control and flexibility in image centering, resulting in a more polished and responsive layout.

Last updated: Nov 25, 2026
★★★★★
4.5 (24 reviews)
Talk to Sales Talk to Sales