I wonder how I could make an image resize along with the browser window, here is what I have done so far (or download the whole site in a ZIP).
This works okay in Firefox, but it has problems in Chrome: the image does not always resize, it somehow depends on the size of the window when the page was loaded.
This also works okay in Safari, but sometimes the image is loaded with its minimum width/height. Maybe this is caused by the image size, I am not sure. (If it loads okay, try to refresh several times to see the bug.)
Any ideas on how could I make this more bulletproof? (If JavaScript will be needed I can live with that, too, but CSS is preferable.)
In IE
onresize
event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
You can use CSS3
scale
property to resize image with css:Further Reading:
This can be done with pure CSS and does not even require media queries.
CSS:
And if you want to enforce a fixed max width of the image, just place it inside a container, for example:
JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).
Initially, I was using the following html/css:
Then I added
class="img"
to the<div>
like this:And everything started to work fine.
2018 solution:
Using viewport-relative units should make your life way easier, given we have the image of a cat:
Now we want this cat inside our code, while respecting aspect ratios:
So far not really interesting, but what if we would like to change the cats height to be the maximum of 50% of the viewport?
The same image, but now restricted to a maximum width of 50vw vw (=viewport width) means the image will be X width of the viewport, depending on the digit provided. This also works for height:
This restricts the height of the image to a maximum of 20% of the viewport.
Set the resize property to both. Then you can change width and height like this: