I have an image that I want to downscale (50% width and height) in a div.
I found something that seems to work in Safari and Firefox, but would like to know if this is the right method to ensure cross browser support.

003.jpg is 800px width & 530px height


#foo-img { height: 100%; }
#foo-div {
    width: 400px; 
    height: 265px; 
    background: gray;


<div id="foo-div">
    <img id="foo-img" src="img/003.jpg" />

2 answers


to save bandwidth and page loading speed, you should really resize the image to the size you want using an image editor.

to do what you're asking the easy way, would just require you to set a new heigth and width in the html:

<img id="foo-img" src="img/003.jpg" height="235" width="400" />

so maybe I'm not understanding what you're really asking?

you could also use the full size image and expose only part of it (cropping) using it as a background image on your div.

#foo-div {
    width: 400px; 
    height: 265px; 
   background :  url(img/003.jpg) no-repeat center center;

explain a little more about why you are doing what you are doing?

Answered about 9 years ago by Tony Crockford
  • Hi Tony, there is no problem for bandwidth etc, as the image in most cases is already in the users cache. I am building a photo app with jQuery. Clicking on a thumbnail will open a Modal popup with the 50% scaled image from the big version. I already worked out a preloader to get the actual width/height of the image when complete. I found out that only if I don't specify the w/h attributes from foo-img I can set height: 100%; when loading is done. Than I set the w/h css from foo-div to half. It works, but I am not sure if it will be cross browser.. Anton PTM about 9 years ago
  • why don't you just size the image with CSS? #foo-img { width: 400px; height: 265px; } Tony Crockford about 9 years ago

You can scale images easily with CSS. Simply:

#img-wrap img {
    display: block;
    width: 200px; 
    /* or a percentage (please note that percentages will relate to 
    it's parent container, not the actual image size) */

You don't have to set the height as this will be adjusted proportionally. Make sure you don't put width/height attributes on the img as these might override.



Answered about 9 years ago by Marko Ivanovski
  • Also you can just set the height, and the width will adjust proportionally. Marko Ivanovski about 9 years ago