How to Center an Image in HTML using CSS

In this guide, I’ll explain 5 different ways to center an image. I hope, the guide will solve your problem on “How to center an image in HTML using CSS”.

How to Center an Image in HTML – Table of Contents

  1. Using Tables
  2. Inline image technique using CSS
  3. Centering background image using CSS
  4. Using “Flex”
  5. The jQuery method (When image or any element size is unknown)

1. Using Tables

Let’s say, you have HTML code like this:

HTML

<table id="container">
 <tr>
   <td><img src="img.jpeg" alt="image" /></td>
 </tr>
</table>

CSS

html, body, #container {
 height:100%;
 width: 100%;
 margin: 0;
 padding: 0;
 border: 0;
}
#container td {
 vertical-align: middle;
 text-align: center;
}

Demo


2. Inline image technique using CSS

HTML

 <img src="img.jpeg" alt="image" />

CSS

 img {
   width: 500px; /* Optional. Use it as per scenario */
   height: 500px; /* Optional. Use it as per your scenario */
   position: absolute;
   margin-top: -250px; 
   margin-left: -250px; 
   top: 50%;
   left: 50%;
}

3. Centering background image using CSS

CSS

 html { 
   background:url(img.jpeg) center center no-repeat;
   width:100%; 
   height:100%;
}

4. Using “Flex”

HTML

<div class="container">
  <div class="vertical">
    <img src="img.jpeg"/>
  </div>
</div>

CSS

div.container {
  display: flex;
  justify-content: center;
}

5. The jQuery method

Add class “centered” to your image element or any other element you want to center.

jQuery

$(document).ready(function() {
  var vertical_align = $(".centered").toArray();
  for (var i = 0; i < vertical_align.length; i++) {

    vertic_width = $(vertical_align[i]).width();
    vertic_height = $(vertical_align[i]).height();
    vertic_martop = parseInt(vertic_height/2);
    vertic_marleft = parseInt(vertic_width/2);
 
    $(vertical_align[i]).css("position","relative");
    $(vertical_align[i]).css("top","50%");
    $(vertical_align[i]).css("left","50%");
    $(vertical_align[i]).css("margin-top","-"+vertic_martop+"px");
    $(vertical_align[i]).css("margin-left","-"+vertic_marleft+"px");
  }
});

Note: All the methods mentioned above are tested.

In this article

Join the Conversation