Search code examples
htmlcsscss-tablesfluid-layoutimage-scaling

Scale large centered images to fit html table height


I'm trying to restrict the height of images within a table. The reason for the table is to allow these images to be aligned vertically and horizontally to the center of the page. The problem I have is that images larger than the browser height disappear of the bottom of the page enlarging the table, I'd like the image to have max-height:100; and scale to fit. It works with the width, but not the height.

Here's what I have so far...

<div id="table">
<div id="cell">
<img src="image.jpg"/>
</div>
</div>

and

html, body{
height:100%;
margin:0;
padding:0;
}

#table{
display:table;
height:100%;
width:100%;
}

#cell{
display:table-cell;
vertical-align:middle;
text-align:center;
background-color:#ccc;
}

img{
max-width:100%;
max-height:100%;
}

Solution

  • You can achieve this without using a table. Here's the basic outline, HTML:

    <body>
        <img src = "image.jpg"/>
    </body>
    

    CSS:

    html, body {
        height: 100%;
        width: 100%;
    }
    body {
        position: relative;
    }
    img {
        position: absolute;
        margin: auto; /*make sure it's centered both vertically and horizontally*/
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        max-width: 100%;
        max-height: 100%;
    }
    

    And a little jsFiddle demo: little link. Note that body must have position: relative; for this to work.

    I hope this helped!