How to Center an Image Horizontally in HTML

This article shows how to center an image horizontally. So, let's dive right in.

Step 1

The first thing we need to do is to create a HTML file and put the following in it.

  1. <html>  
  2. <head>  
  3.     <title></title>  
  4. </head>  
  5. <body>  
  6.     <img src="images/1.jpg" width="300px" height="300px">  
  7.     <p>  
  8.         Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod  
  9.         tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,  
  10.         quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo  
  11.         consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse  
  12.         cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non  
  13.         proident, sunt in culpa qui officia deserunt mollit anim id est laborum.  
  14.     </p>  
  15. </body>  
  16. </html>  
Save this HTML file and give it the name Index.html.

Open the file in a browser.


Currently our image is aligned to its default position.

Step 2

The next step is to create an external stylesheet file and give it the name style.css and in the head section of your HTML file write the following:
  1. <link rel="stylesheet" type="text/css" href="css/style.css">  
The preceding is nothing but the address location of our CSS file.

Step 3

There are two ways to center an image horizontally.
  1. Add an image element inside the div container element.

    Add image element

    Create a new rule in style.css with the following:


    Refresh the page.

    Refresh the page

  2. Another way to do it is by changing the display property of the image element to a block level element.

    But first remove the img element from the div element.


    Refresh the page and you will see the image is now back to its initial position.

    initial position

    In the CSS file create a new rule and write the following:


The margin is set to 0 (top), 0 (left), 0 (bottom) and 0 (right).

Or you can also say:

css file

Refresh the page.


So, in this article we saw how to center an image horizontally.

I hope you like it and find this helpful. Thank you.


Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now