Maintain Image Aspect Ratio When Changing Height

CSS force image resize and keep aspect ratio

img {  display: block;  max-width:230px;  max-height:95px;  width: auto;  height: auto;}
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p><img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png">

Maintain image aspect ratio when changing height

For img tags if you define one side then other side is resized to keep aspect ratio and by default images expand to their original size.

Using this fact if you wrap each img tag into div tag and set its width to 100% of parent div then height will be according to aspect ratio as you wanted.

http://jsfiddle.net/0o5tpbxg/

* {
margin: 0;
padding: 0;
}
.slider {
display: flex;
}
.slider .slide img {
width: 100%;
}

Force an image to fit and keep aspect ratio

You can try CSS3 object-fit, and see browser support tables.

CSS3 object-fit/object-position Method of specifying how an object (image or video) should fit inside
its box. object-fit options include "contain" (fit according to aspect
ratio), "fill" (stretches object to fill) and "cover" (overflows box
but maintains ratio), where object-position allows the object to be
repositioned like background-image does.

JSFIDDLE DEMO

.container {  width: 200px; /*any size*/  height: 200px; /*any size*/}
.object-fit-cover { width: 100%; height: 100%; object-fit: cover; /*magic*/}
<div class="container">  <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg"></div>

How to resize images proportionally / keeping the aspect ratio?

Have a look at this piece of code from http://ericjuden.com/2009/07/jquery-image-resize/

$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height

// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}

// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
});
});


Related Topics



Leave a reply



Submit