Vertical and horizontal center img in div

This example shows how an image (img) can be vertically and horizontally centered inside a div. At the same time it illustrates how to resize the image to fit inside the div.

A live view of this code can be seen here. 

<html>
  <head>
    <title>Vertically aligned img in div</title>
    <style type="text/css">
      #container {
        position: absolute;
        width: 600px;
        height: 600px;
        background-color: lightyellow;
        vertical align: middle;
      }  

      #container img {
        max-width: 80%;
        max-height: 80%;
        margin: auto;
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
      }


      p {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <img src="sl-buss-6050.jpg" alt="SL-buss 6050" title="SL-buss 6050">
      <p>The yellow box is here to show the div</p>
    </div>
  </body>
</html>

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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

9 + 12 =