How to put image in image size div div max then div or min then div

How do I put an image in a div? Image size can be max than div or min, then div.

html code

<div class="main">
  <img scr="image.jpg">
</div>

CSS code

.main{
  height:200px;
  width:200px;
}

img{
  // answer code
}

How to set css image with the following parameters:

  • image height 100 and width 100
  • image height 300 and width 300
+5
source share
2 answers

You can use: -

img { max-width: 100%; height: auto; } // This would help you to automatically fit the image.

EDIT:

The above css code will help you for images larger than div. But not suitable for images that are smaller than a div. A bit of jQuery is required to reach your goal, please find it below: -

$(document).ready(function(){
    imageWidth = $('.main img').width();
    parentWidth = $('.main').width();
    if (imageWidth > parentWidth) {
        $('.main img').css('width', '100%');
    }
});

What happens when an image is smaller than a div, it resizes and fits the div according to your requirement.

css, script, .

+8

,   img{ width: 200px; height: 200px; }

,

.main {
    width: 200px;
    height: 200px;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}
img {
    max-width: 200px;
    max-height: 200px;
    /* IE7 doesn't support display: table-cell property? so hack */
    *margin-top: expression((parentNode.offsetHeight.offsetHeight/2)-(parseInt(this.offsetHeight)/2) <0 ? "0" :(parentNode.offsetHeight/2)-(parseInt(this.offsetHeight)/2) +'px');     }

http://jsfiddle.net/qBDT4/1/

0

All Articles