Arvo Bowen
Arvo Bowen

Reputation: 4955

Using CSS to make image size 100% to height of container

I have looked around reading solution after solution and trying all kinds of things but never getting this to work right...

I want the image to end up being dynamically resized based on the current height of the browser window. Currently using the code below the image is the original height and ends up being LARGER than the browser window causing a vertical scrollbar to appear.

Note: Please keep in mind I want this accomplished using the same amount of of tables and cells. Please do not give me a single table solution.

<html>
  <head>
    <style>
      body
      {
        text-align: center;
        margin: 0px;
        margin-left: auto;
        margin-right: auto;
      }
      table.one
      {
        border-collapse: collapse;
      }
      table.two
      {
        border-collapse: collapse;
      }
      img
      {
        max-height: 100%;
      }
    </style>
  </head>
  <body>
    <table class="one" cellpadding=0>
      <tr>
        <td>
          <table class="two" cellpadding=0>
            <tr>
              <td>
                <img src="myimage.jpg">
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>

Upvotes: 3

Views: 14768

Answers (3)

asimes
asimes

Reputation: 6130

Add img {display:block;}. This should get rid of a few pixels at the bottom.

Also td {padding:0;} will do the same thing as cellpadding=0 but is a HTML5 solution.

Edit: Try this out then, it appears to be the same for me:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>Untitled</title>
    <style type="text/css">
        body {margin:0; padding:0;}
        table {border-collapse:collapse; border-spacing:0;}
        td {padding:0;}
    </style>
</head>
<body>
    <table style="background:#888;">
        <tr style="background:#f88;">
            <td style="background:#8f8;">I should</td>
            <td style="background:#88f;">look the</td>
        </tr>
        <tr style="background:#ff8;">
            <td style="background:#8ff;">same across<td/>
            <td style="background:#f8f;">different browsers</td>
        </tr>
    </table>
</body>
</html>

Upvotes: 1

Mark Ryan Sallee
Mark Ryan Sallee

Reputation: 293

You can use viewport units to resize based on the size of the browser window.

img {
    max-height: 100vh;
}

Upvotes: 8

Ashwani
Ashwani

Reputation: 3491

Try this with Jquery imagescale:

<img id="img1" src="myimage.jpg">

    $(document).ready(function(){ 
      $('#img1').imgscale({ 
        parent : '.parentcontainer',
        fade : 1000 
      }); 
    });

keep remember define your parent container width and height first as:

.parentcontainer {
  height: 100%; 
  width: 100%; 
}

Upvotes: -3

Related Questions