Morgan Cheng
Morgan Cheng

Reputation: 76078

How to stretch image to fit square in web page?

The web page needs to display some images. And, the images are supposed to be displayed to fit square (90 * 90 pixels). Unfortunately, size of the images are unpredictable. They might be 80*100 or 100*80 or 90 * 110.

The requirement is to stretch image as:
1) If image has width 45 and height 100, stretch its width to 90 and height to 200. Display its top 90 pixels.
2) If image has width 100 and height 45, stretch its width to 200 and height to 90. Display its left 90 pixels.

In a word, always left-top part of the image with 90*90 size.

What's the solution for it in JavaScript and CSS? Thanks

Upvotes: 1

Views: 10882

Answers (2)

simonbs
simonbs

Reputation: 8042

Would this do it?

<div style="width:90px;height:90px;border:1px solid #000;background-position:left top;background-image:url('myImage.jpg');background-size:100%;"></div>

Example on http://snuzzer.dk/pub/fit_image_to_div.html

UPDATE:

I have changed it to use JavaScript instead. This should solve the issue with the width/height no showing correct wehn using the CSS-only approach. Take a look at http://snuzzer.dk/pub/fit_image_to_div.html for an example.

<script type="text/javascript">
function fitImage(src) {
    var image = new Image();
    image.src = src;
    var height = image.height;
    var width = image.width;

    if(width > height) { // Image is wider than it's high
        scale = 90 / height;
    }
    else { // Image is higher than it's wide
        scale = 90 / width;
    }

    image.width = width * scale;
    image.height = height * scale;

    document.getElementById('info').innerHTML = width + 'x' + height + ' => ' + image.width + 'x' + image.height;

    document.getElementById('container').style.backgroundImage = 'url(' + image.src + ')';
    document.getElementById('container').style.backgroundSize = image.width + 'px ' + image.height + 'px';
}
</script>
<div style="width:90px;height:90px;border:1px solid #000;background-position:left top;" id="container"></div>
<div id="info"></div>
URL to an image: <input type="text" id="url" style="width:400px;" />
<br />
<input type="button" value="Fit images" onClick="fitImage(document.getElementById('url').value)" />

Upvotes: 2

Amr Elgarhy
Amr Elgarhy

Reputation: 69042

You just need to put the needed width and height in the image html tag like this

<img src="myimgae.jpg" width="90" height="90"/>

Upvotes: 0

Related Questions