Skip to main content

Centering Images

Images can be centered in three ways: horizontally, vertically, or both at the same time.

CSS offers several methods for doing it.


Center an Image Horizontally

Two common choices for centering an image horizontally are margin: auto and display: flex.

Using margin: auto

margin: auto is the first of the two options for horizontal centering.

It has no effect on inline elements, and <img> is inline by default, so the image needs display: block first.

A width is also required, and it has to be narrower than the page.

Prompt
Create a page with an image centered horizontally using margin: auto. Set the image to display: block with margin: auto and width: 50%.
Output: complete HTML page

Using display: flex

display: flex offers a second route to horizontal centering.

Wrap the <img> element in a <div>, then give that container these two declarations:

  • display: flex
  • justify-content: center (horizontal centering of the image)

Finally, choose a width for the image that is narrower than the width of the page.

Prompt
Create a page with an image centered horizontally using flexbox. Place the image inside a div container with display: flex and justify-content: center. Set the image width to 50%.
Output: complete HTML page

Vertical and Horizontal Centering

True centering means both directions at once, vertical and horizontal. Either display: flex or display: grid can do it.

Using display: flex

With flexbox, centering an image on both axes at once takes these declarations together:

  • display: flex
  • justify-content: center (horizontal centering)
  • align-items: center (vertical centering)
  • height: 600px (how tall the container is)

Put the <img> inside a <div> container, and keep the image's width below the container's width.

Prompt
Create a page with an image centered both vertically and horizontally using flexbox. Place the image inside a div with display: flex, justify-content: center, align-items: center, height: 600px, and a 1px solid black border. Set the image width to 50%.
Output: complete HTML page

Using display: grid

With grid, centering an image on both axes at once takes this combination:

  • display: grid
  • place-items: center (both horizontal and vertical centering)
  • height: 600px (how tall the container is)

Here too, the <img> goes inside a <div> container, and the image gets a width narrower than the container's.

Prompt
Create a page with an image centered both vertically and horizontally using CSS grid. Place the image inside a div with display: grid, place-items: center, height: 600px, and a 1px solid black border. Set the image width to 50%.
Output: complete HTML page