There are three ways to center an image in HTML by using CSS properties – text-align
, margin
, and flex
Table of Contents
Text-align
This is a common CSS property we use to make text center-aligned in an element. We can use it for an image to make it center horizontally as well.

div{ text-align: center; }
<div style="width: 500px; height: 500px; margin: 150px auto;"> <div style="border: 1px solid; text-align: center;"> We can center both text and image with <code>text-align: center</code> <img src="https://www.tldevtech.com/wp-content/uploads/2020/06/potion_medium2_2-300x300.png" /> </div> </div>
Flex
You can also center an image using the flex properties.

div { display: flex; justify-content: center; }
<div style="border: 1px solid; display: flex;justify-content: center;"> <img src="https://www.tldevtech.com/wp-content/uploads/2020/09/sword_blue2.png" width="100" /> </div>
Margin
Magin with value as auto can make any element center horizontally within its parent.

<div style="border: 1px solid;"> <img src="https://www.tldevtech.com/wp-content/uploads/2020/08/Asset-10spear.png" /> </div> <style type="text/css"> img { display: block; width: 150px; margin-left: auto; margin-right: auto; margin-top: 50px; margin-bottom: 50px; } </style>
The margin property of the img tag above can be written as margin: 50px auto;
Center an image horizontally and vertically
If you know the height of the image’s parent, you can use the margin attribute to make the image center horizontally and vertically. The example above sets margin top and bottom with 50px.
Another method is to use flex.

<div class="wrapper"> <img src="https://www.tldevtech.com/wp-content/uploads/2020/06/potion_medium1_3.png" width="150" /> </div> <style type="text/css"> .wrapper{ height: 100%; display: flex; align-items: center; justify-content: center; border: 1px solid red; } </style>