0

I have an image within a div and I want either the image to shrink to either 100% width or 100% height of the containing div. As suggested here, I've tried setting both max-height and max-width to 100%. This still causes some overflow (and I don't want to crop the image with overflow:hidden). The image is floated within the div.

Is it possible to accomplish this? My code is below. Am I doing something wrong?

div#_content div#_thumbnails div {
  padding:2px;
  display:inline-block;
  min-width:10%;
  max-width:25%;
  min-height:80px;
  max-height:125px;
  text-align:center;
}
div#_content div#_thumbnails img {
  display:inline;
  padding:2px;
  float:left;
  max-height:100%;
  max-width:100%;
}

In the javascript below, imgs is a list of URL's. thumbnails is a mother-div that the containers will sit in.

for (i in imgs) {
  if (imgs[i]) {
    var new_img = document.createElement('IMG'),
      container = document.createElement('DIV')
    new_img.setAttribute('alt', "image"+i.toString())
    new_img.setAttribute('src', imgs[i])
    container.appendChild(new_img)
    thumbnails.appendChild(container)
  }
}

I hope this is isn't a dumb question, but I've searched and none of the suggestions I've found have worked.

Community
  • 1
  • 1
Eric H.
  • 6,894
  • 8
  • 43
  • 62

2 Answers2

1

Please try:

<style type="text/css">
#thumbContainer {
    position:relative;
}
.thumb{
    position:relative;
    float:left;
    width: 100%;
    height: auto;
}
.thumb img {
    background-size: cover !important;
    width: 100%;
    height: auto;
}
</style>

<div id="thumbContainer">
    <div class="thumb"><img src="http://3.bp.blogspot.com/_ABFjy8u6h9s/TStw8-_4j1I/AAAAAAAACE0/cKm4ZiIFilk/s1600/NATUREZA+01.jpg" /></div>
    <div class="thumb"><img src="http://3.bp.blogspot.com/_ABFjy8u6h9s/TStw8-_4j1I/AAAAAAAACE0/cKm4ZiIFilk/s1600/NATUREZA+01.jpg" /></div>
    <div class="thumb"><img src="http://3.bp.blogspot.com/_ABFjy8u6h9s/TStw8-_4j1I/AAAAAAAACE0/cKm4ZiIFilk/s1600/NATUREZA+01.jpg" /></div>
</div>

(http://jsfiddle.net/ahjjg/)

Adittional, I suggest background insted of <img>.

Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74
  • I am actually trying to keep the .thumb's centered within thumbContainer, so my solution deviated a bit. Going with background is much easier (I went background-size:contain; and background-position:center;). Thanks. – Eric H. Apr 10 '12 at 16:37
0

If you are using PHP then this is the best solution for you

http://www.welancers.com/perfect-solution-for-image-resizing-based-on-width-height/

aslamdoctor
  • 3,753
  • 11
  • 53
  • 95