CSS scale down image to fit in containing div, without specifing original size

Muteking picture Muteking · Sep 4, 2013 · Viewed 245.4k times · Source

I want to have a website where I can upload images of different sizes to be displayed in a jquery slider. I can't seem to fit (scaling down) the image in a containing div. Here's how I'm intending to do it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title> 
<link rel="stylesheet" type="text/css" href="Imtest.css"/>
</head>

<body>

<div id="wrapper"> 

<div id="im"><img src="Images/Scarpa2_1.jpg" /></div>

</div>  
</body>
</html>

And the CSS

#wrapper {
    width: 400px;
    height: 400px;
    border: 2px black solid;
    margin: auto;
}

#im {
    max-width: 100%;
}

I've tried to set the max-width of my image to 100% in CSS. But that doens't work.

Answer

dc5 picture dc5 · Sep 4, 2013

You can use a background image to accomplish this;

From MDN - Background Size: Contain:

This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.

Demo

CSS:

#im {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url("path/to/img");
    background-repeat: no-repeat;
    background-size: contain;
}

HTML:

<div id="wrapper">
    <div id="im">
    </div>
</div>