Skip to content

Center image in div vertically and horizontally | Example code

  • by

Center image in div vertically and horizontally use margin: auto; in CSS. In HTML webpage set left and right margin to auto and make it into a block element.

Simple Example code:

Image is in a same folder with webpage.

<!DOCTYPE html>
<html>
<head>
    <style>
        #img1 {
          display: block;
          margin-left: auto;
          margin-right: auto;
      }
  </style>
</head>
<body>

    <h2>Center an Image CSS HTML</h2>

    <img id="img1" src="bg.jpg" alt="Image space" style="width:40%">

</body>
</html>

Output:

Center image in div vertically and horizontally

Example of CSS center image in div

Example code of CSS center image vertically and horizontally in div.

<!DOCTYPE html>
<html>
<head>
    <style>
        #body1 {
          margin: 0;
      }

      #over img {
          margin-left: auto;
          margin-right: auto;
          display: block;
      }
  </style>
</head>
<body id="body1">

    <div id="over" style="position:absolute; width:100%; height:100%">
        <img src="bg.jpg">
    </div>

</body>
</html>

Do comment if you have another example or doubts on this topic.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading