center an HTML image element using CSS

How to center an HTML image element using CSS?

You can center an HTML image element in different ways using CSS.

1. Using text-align: center; property to center an image

By default, an HTML image element is an inline element, so the text-align: center; can center an image element.

Add the text-align: center; to the parent element of the image element which you want to center.

<style>
  .image-container{
    text-align: center;
  }
  .image{
    width: 200px;
  }
</style>

<div class="image-container">
  <img class="image" src="./image.jpg" alt="test image">
</div>
HTML and CSS centered image

2. Using CSS margin to center an image

To center an image using margin, you need to convert the image to a block element, then you can apply margin.

  • display: block; – converts to a block element.
  • margin: 0 auto; – the top and bottom margins are 0, and the left and right margins are auto.
<style>
  .image{
    display: block;
    margin: 0 auto;
    width: 200px;
  }
</style>

<div class="image-container">
  <img class="image" src="./image.jpg" alt="test image">
</div>
HTML and CSS centered image

3. CSS Flexbox and Grid can center an image

First, you have to apply the flexbox or grid to the parent element of the image, then use the justify-content: property to center the image.

  • display: flex; – Implements the Flexbox.
  • display: grid; – Implements the grid system.
  • justify-content: center; – moves the content (image) to the center. This property works with both Flex and Grid.
<style>
  .image-container{
    display: flex; /* You can replace this line to - display: grid; */
    justify-content: center;
  }
  .image{
    width: 200px;
  }
</style>

<div class="image-container">
  <img class="image" src="./images/image.jpg" alt="test image">
</div>
HTML and CSS centered image

Center an HTML image horizontally as well as vertically

All three examples above center an image horizontally. Now we will see how you can center an HTML image horizontally as well as vertically.

Using CSS Flexbox or Grid you can easily center an image element horizontally as well as vertically.

<style>
  .image-container{
    display: flex; /* You can replace this line to - display: grid; */
    justify-content: center;
    align-items: center;

    height: 400px;
    border: 2px solid black;
  }
  .image{
    width: 200px;
  }
</style>

<div class="image-container">
  <img class="image" src="./images/image.jpg" alt="test image">
</div>
css center image horizontally and vertically