Right now, I\'m using max-width to scale images to fit. However, they don\'t scale proportionally. Is there a way to cause this to happen? I\'m open to Javascript/jQuery.
<I had to do this with the following requirements:
The closest I came up with is this terrible contraption. It requires three elements and two inline styles, but as far as I know this is the best way to scale images proportionally. All the height: auto;
suggestions here negate the point of specifying the image dimensions on the server side and cause the content to jump around while loading.
.image {
position: relative;
}
.image img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<!-- container element with max-width prevents upscaling -->
<div class="image" style="max-width: 640px;">
<!-- div with padding equal to the image aspect ratio to make
the element the correct height -->
<div style="padding-top: 75%;"></div>
<!-- img scaled to completely fill container -->
<img src="//placebear.com/640/480" />
</div>
https://jsfiddle.net/Lqg1fgry/6/ - The "Hello" is there so you can see if the content after the image jumps around.
Contrary to the accepted answer, you can do this without specifying the size in the HTML. It can all be done in CSS:
#content img {
max-width: 100px;
width: 100%;
height: auto;
}
when setting up constant width use:
height: auto
function resizeBackground() {
var scale=0;
var stageWidth=$(window).width();
var newWidth=$("#myPic").width();
var stageHeight=$(window).height();
var newHeight=$("#myPic").height();
if( $(window).width() > $(window).height() ) {
scale = stageHeight/newHeight;
scale = stageWidth/newWidth;
} else {
scale = stageWidth/newWidth;
scale = stageHeight/newHeight;
}
newWidth = newWidth*scale;
newHeight = newHeight*scale
$("#myPic").width(newWidth);
$("#myPic").height(newHeight);
}
You need to specify the original width and height:
<img src="/whatever" width="100" height="200" alt="Whatever" />
And then use something like this in the CSS:
#content img { max-width: 100%; height: auto }
You could try this with jQuery if you don't have the width and height up front, but your mileage may vary:
$(function(){
$('#content img').load(function(){
var $img = $(this);
$img.attr('width', $img.width()).attr('height', $img.height());
});
});
Obviously replace #content
with whatever selector you want to scope the functionality to.
Here's how to do it with no Javascript. Set your max-width
to the length you want.
#content img {
max-width: 620px;
height: auto;
}
This worked for me tested on a Mac with Firefox 28, Chrome 34 and Safari 7 when I had no width or height settings explicitly set in the img
tags.
Don't set your width in CSS to 100% after the max-width
setting as one person suggested because then any images that are narrower than the width of the container (like icons) will be blown up much larger than desired.