1

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 original ratio of image.But, image size should not exceed than original size,using jQuery or Javascript.

<div>
    <img src="logo.jpg"/>
</div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Gmv
  • 2,008
  • 6
  • 29
  • 46

3 Answers3

0

use max-width and max-height css property.

Ravi
  • 316
  • 7
  • 17
0

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/

Tushar
  • 85,780
  • 21
  • 159
  • 179
0
Try this,

img{
    max-width:100%;
    max-height:100%;
}
Nitekurs
  • 441
  • 5
  • 11