CSS force image resize and keep aspect ratio

前端 未结 23 865
野趣味
野趣味 2020-11-22 10:04

I am working with images, and I ran across a problem with aspect ratios.

\"\"

23条回答
  •  粉色の甜心
    2020-11-22 10:50

    This will make image shrink if it's too big for specified area (as downside, it will not enlarge image).

    The solution by setec is fine for "Shrink to Fit" in auto mode. But, to optimally EXPAND to fit in 'auto' mode, you need to first put the received image into a temp id, Check if it can be expanded in height or in width (depending upon its aspect ration v/s the aspect ratio of your display block),

    $(".temp_image").attr("src","str.jpg" ).load(function() { 
        // callback to get actual size of received image 
    
        // define to expand image in Height 
        if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
            $(".image").css('height', max_height_of_box);
            $(".image").css('width',' auto');
        } else { 
            // define to expand image in Width
            $(".image").css('width' ,max_width_of_box);
            $(".image").css('height','auto');
        }
        //Finally put the image to Completely Fill the display area while maintaining aspect ratio.
        $(".image").attr("src","str.jpg");
    });
    

    This approach is useful when received images are smaller than display box. You must save them on your server in Original Small size rather than their expanded version to fill your Bigger display Box to save on size and bandwidth.

提交回复
热议问题