Posts

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>

Div with width 100% and margins or padding gets wider than 100% [solved]

If a div is set to width (or height) 100% and margins or padding are added, it will be wider than 100% causing the scrollbars to appear in the browser. 

For example like this (click here to view live sample):

<html>
<head>
  <style type="text/css">
    body, html {
      width: 100%;
      border: 0;
      margin: 0;
      padding: 0;
    }
    #wrapper {
      width: 100%;
      margin: 0;
      padding: 0;
      border: 0;
    }
    #container {
      width: 100%;
      margin: 10px;
      padding: 0;
      border: 0;
      background-color: lightblue;
    }
  </style>
</head>
<body>
  <div id="wrapper">
    <div id="container">
      <h1>Div taking more than 100% space</h1>
      <p>It demonstrates a div that is taking up more than 100%. Notice the horizontal scroll bar below.</p>
    </div>
  </div>
</body>
</html>

The solution is to set the inner container width to auto instead of 100%, like this (click here to view live sample):

<html>
<head>
  <style type="text/css">
    body, html {
      width: 100%;
      border: 0;
      margin: 0;
      padding: 0;
    }
    #wrapper {
      width: 100%;
      margin: 0;
      padding: 0;
      border: 0;
    }
    #container {
      width: auto;
      margin: 10px;
      padding: 0;
      border: 0;
      background-color: lightblue;
    }
</style>
</head>
<body>
  <div id="wrapper">
    <div id="container">
       <h1>Div NOT taking more than 100% space</h1>
       <p>It demonstrates a div that is NOT taking up more than 100%. Notice the absence of the horizontal scroll bar below.</p>
       <p>The difference/solution is to set the inner div with width: auto.</p>
    </div>
  </div>
</body>
</html>