Skip to content Skip to sidebar Skip to footer

Automatically Change The Image Size In The Original Ratio Of The While Change The Size Of That Images Parent Element

A div tag have a image.I have to change the div width and height.If I change the width and height of the tag, that image's width and height will be automatically change in the orig

Solution 1:

You might want to call this function on window.load:

$('img:visible').each(function() {
    // For visible images only
    var imageWidth,
        imageHeight,
        aspectRatio;

    var parentWidth = $(this).parent().width(),
        parentHeight = $(this).parent().height();

    if (this.naturalWidth > parentWidth || this.naturalHeight > parentHeight) {
        aspectRatio = this.naturalWidth / this.naturalHeight; // Actual image width and height

        if (this.naturalWidth > this.naturalHeight) {
            imageWidth = parentWidth - 50; // Leave margin
            imageHeight = imageWidth / aspectRatio;
        } else {
            imageHeight = parentHeight - 10; // Leave some space
            imageWidth = imageHeight * aspectRatio;
        }

        $(this).css({
            'width': imageWidth,
            'height': imageHeight
        });
    }
});

Demo: https://jsfiddle.net/tusharj/onytgawp/


Solution 2:

use max-width and max-height css property.


Solution 3:

Try this,

img{
    max-width:100%;
    max-height:100%;
}

Post a Comment for "Automatically Change The Image Size In The Original Ratio Of The While Change The Size Of That Images Parent Element"