Anna Riekic
Anna Riekic

Reputation: 738

Responsive images, scale down only

I'm trying to work out how to make images responsive but scale down only, all solutions I have found so far use max-width:100% or max-width:??px but these also stretch the image to its parent container and that's not the result I'm after.

I currently have a jquery fix:

 var ww = $(window).width(),
     iw = $('img').width();

 if(ww < iw) {
  $('img').css('width',ww - 20);
 }

but would like a css only solution.

So say I have an image with a 640px width if browser window is wider than 640px the image should remain 640px wide and not stretched to fit its parent container, but if the browser window is smaller then and only then should the image be responsive to fit inside the browser window.

Upvotes: 1

Views: 329

Answers (3)

MrGrigri
MrGrigri

Reputation: 314

Okay...I'm refining my answer for you situation. First of all, you need to set some bounds first in the css like this:

img.specialClass {
  width: 100%;
}

And now here comes the tricky part. I'm using jQuery here for ease of use:

$('img.specialClass').each(function() {
  var $img = $(this);
  var fakeImg = new Image;
  fakeImg.src = $img.attr('src');
  fakeImg.onload = function() {
    var width = this.naturalWidth;
    $img.css('max-width', width);
  }
});

I would initially hide the image because the max-width is not being set until they are fully loaded. Please let me know if you have any further questions.

Upvotes: 0

Samuel Cook
Samuel Cook

Reputation: 16828

Something like this should work:

<style type="text/css">
img{width:640px;}

@media (max-width: 640px) 
{
    img{width:100%;}
}
</style>

<img src="https://www.google.com/images/srpr/logo11w.png">

Upvotes: 0

Stickers
Stickers

Reputation: 78746

It should do it with max-width, see the demo.

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

http://jsfiddle.net/d5mLhdpp/

Upvotes: 3

Related Questions