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.
If possible, is there a way to do this without knowing the original dimensions of the image (maybe determine this using Javascript/jQuery)?
In that situation we can use CSS max-width or width to fit the image. Use max-width: 100% to limit the size but allow smaller image sizes, use width: 100% to always scale the image to fit the parent container width.
For proportional resizing purposes, it makes matters extremely simple: Define the width of an element as a percentage (eg: 100%) of the parent's width, then define the element's padding-top (or -bottom) as a percentage so that the height is the aspect ratio you need. And that's it!
To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.
Use the auto Value for Width and the max-height Property to Resize the Image in CSS. We can use the auto value to the width and set the max-height property to specify the width of an image to fit in a container. We will shrink the height of the image to the height of the container.
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;
}
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.
when setting up constant width use:
height: auto
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With