Jackson
Jackson

Reputation: 1184

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!

Upvotes: 10

Views: 6283

Answers (2)

David
David

Reputation: 21

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

            }
}

Upvotes: 2

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827178

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.

Upvotes: 18

Related Questions