How to Center an Image Horizontally and Vertically with HTML and CSS

There are three ways to center an image in HTML by using CSS properties – text-align, margin, and flex

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>

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close