Can you resize the image proportionally using CSS (or JS / JQ) if width and height are already set in HTML

Is there a way to proportionally resize the image if the height and width are already defined in the tag?

Obviously if I have an image tag like:

<img src="whatever.jpg" width="500" height="350">


and use max-width like:

img { max-width: 200px; }


I am getting a 200px by 350px image.

I would prefer a pure CSS solution (which I'm pretty sure doesn't exist), but could use Javascript and / or jQuery as well.


source to share

3 answers

Of course, you are setting another dimension to auto






I don't think CSS can do this.

With jQuery, this is trivial. You don't even need the width and height attributes in HTML, although it's usually convenient to have them.

    var real_width = $(this).width();
    var real_height = $(this).height();
    var max_width = $(this).css("max-width");  // Or just say 200
    if (real_width > max_width) {
        var ratio = real_width / real_height;
        $(this).height(max_width / ratio);


I have not tested this code, so there may be small bugs, but the general idea is there.

Edit: In some browsers $(document).ready()

will fire before all images are loaded. If you have an image with no explicit width and height attributes, it might be a problem because it $(this).width()

will return 0. In this case, just make sure all images have width and height attributes, or add this code to instead $("img").load()




// parameters
// obj      : usually $('img') object I presume.
function thumbnail_resize(obj){
    var maxW = 50;      var maxH = 50;
    var wid = obj.width();
    var hei = obj.height();

    if( wid > maxW ) {
        hei *= (maxW / wid);
        wid = maxW;
    if( hei > maxH ) {
        wid *= (maxH / hei);
        hei = maxH;
    obj.attr('width', wid);
    obj.attr('height', hei);

    delete maxW, maxH, wid, hei;




All Articles