I dealt a lot with this problem. Generally the solution is to put the img inside a div, and limit only the width of the div that contains the image. The image should have "width: 100%". Thus, the image will be proportional, and with the width of the div
This container div must have a well defined width, it can be both in pixels and in percentage, but there must be a width.
Follow my CSS, I use two div's, one inside the other, for reasons I will describe further below. The outer div (cartimg) is 55% wide and centered thanks to "margin: auto", but you could use float or another method of positioning the div.
#body div.cartimg {
margin: auto;
width: 55%;
text-align: center;
}
#body div.cartimg div.cartimg2 {
width: 100%;
margin: auto;
text-align: center;
padding: none;
}
#body div.cartimg img {
width: 100%;
margin-left: 0em;
margin-top: 0em;
margin-right: 0em;
margin-bottom: 0em;
}
An additional problem I faced was this: I have images of different widths and heights, and I would like to limit the size of the image in the two dimensions. A wide image can occupy 55% of the width, but a very narrow image would be "stretched" to cover 55% and would be very vertical. This is particularly unpleasant on a mobile screen.
One solution is to manually change the image size (width less than 100%), another is to recalculate using Javascript (dynamically), the solution I adopted was to calculate the image aspect ratio in PHP and change the width container of the cartimg2 container to limit its height , if the image is higher than 16: 9. (Attempts to limit the height directly did not work very well.)
Here is the relevant PHP code:
function get_container_width($addr)
{
$tallest = 16.0 / 9.0;
$container_width = 100;
if ($addr[0] == '/') {
$addr = $_SERVER["DOCUMENT_ROOT"] . $addr;
}
list($width, $height) = getimagesize($addr);
if ($width > 0 && $height > 0) {
$prop = $width / $height;
if ($prop < $tallest) {
// image is 'tall', or thin
// we need to limit width to limit height indirectly
$container_width *= $prop / $tallest;
}
}
return $container_width;
}
$container_width = get_container_width($addr);
echo("<div id='$name' class=cartimg>");
echo("<div id='hdiv_$name' style='width: $container_width%;' class=cartimg2>\n");
echo("<a href='$addr' class=noarrow>\n");
echo("<img src='$addr' alt='$desc'>\n");
echo("</a>\n");
echo("</div>");
echo("<i>$desc</i>\n");
echo("</div>");
The solution using background instead of img also works to limit height and width, except that you are playing the web semantics outside (Google finds the images by the img tag, and their descriptions by the alt attribute).