Is there a way to fix the aspect ratio of images given a smaller width using css? Maybe by using jQuery / javascript?
Thanks!
The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.
In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
With plain CSS, you could set only one dimension of the images, either width
or height
and set the other as auto
, e.g.:
.thumb {
width:200px;
height:auto;
}
The images will have a fixed 200px width, and the height will depend on the aspect ratio.
Here is the jQuery solution ;)
function fixImage(elm) {
elm = $(elm);
var x = elm[0];
var allowedHeight = 80;
var allowedWidth = 80;
if (width > height) {
elm.css('width', allowedWidth + 'px');
elm.css('height', 'auto');
}
else {
elm.css('height', allowedHeight + 'px');
elm.css('width', 'auto');
}
}
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