html

How to center an image in html

Aligning your images in an appropriate position with respect to other content on your web pages is highly important. This proper alignment defines and enhances the structure of a website. In HTML, there are various ways with which you can center an image. These approaches have been discussed here in this blog.

How to center an Image using the text-align property

For the purpose of centering an image using the text-align property consult the example below.

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Center an Image in HTML</title>
</head>
<body>

<div style="text-align: center;">
  <img src="sky.jpg" alt="Sky" style="width: 350px; height: 350px;">
</div>

</body>

In the above code, we are making a div container and placing our image inside that container using the <img> tag. This attribute provides an inline styling to the image. Then to center the image we are using the style attribute of the div container to set the text-align property to center. Using this property on the <img> tag will have no effect, therefore, you have to wrap the image inside a container and assign this property to that container.

Output

This is how you center an image.

How to center an Image using margins

Another way of assigning your image a centered position is by using margin-right and margin-left properties as we have shown in the code snippet below.

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Center an Image in HTML</title>
</head>
<body>

<img src="sky.jpg" alt="Sky" style="display: block; margin-right: auto; margin-left: auto;>

</body>

Here we are first of all providing the image to the src attribute of the tag then afterwards using the style attribute we are making the image a block-level element by setting its display to block and then margin-right, and margin-left properties were set to auto.

Output

The output displays a centered image.

Conclusion

In order to center an image in HTML either use the text-align property or the margin-right and margin-left property. When using the text-align property wrap the image inside a div container and then using the style attribute set the text-align property of the container to center, whereas, in the case of using the margin properties first set the display of the image to block and then assign auto to both margin-right, and margin-left properties.

About the author

Naima Aftab

I am a software engineering professional with a profound interest in writing. I am pursuing technical writing as my full-time career and sharing my knowledge through my words.