Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep aspect ratio with image width in css

Is there a way to fix the aspect ratio of images given a smaller width using css? Maybe by using jQuery / javascript?

Thanks!

like image 911
Jackson Avatar asked Jan 04 '10 04:01

Jackson


People also ask

How do I resize an image using CSS without losing the aspect ratio?

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.

How do I keep aspect ratio in CSS?

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.

How do I fit an image IMG inside a div and keep the aspect ratio?

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.


2 Answers

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.

like image 86
Christian C. Salvadó Avatar answered Sep 18 '22 13:09

Christian C. Salvadó


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');

            }
}
like image 21
David Avatar answered Sep 18 '22 13:09

David