Reputation: 17778
I can make an image scale responsively to a parent div on smaller screens but still limit to an explicit max width:
img {
max-width: 500px;
width: 100%;
}
However, if the image is smaller than the parent div, it is still stretched to fill the div.
Is there a way to have it scale to 100% only when it is larger and maintain its original dimensions when it is smaller, without knowing the image's dimensions beforehand?
Upvotes: 9
Views: 27648
Reputation: 5666
In case you are using Bootstrap (version 3.x, perhaps other versions as well) you can also use
class='img-responsive'
on your <img>
tag to resize it to the parent element's size.
Upvotes: 6
Reputation: 584
You can put the image inside a div and apply these styles:
<div><img></div>
div{max-width: 500px}
img{max-width: 100%}
example on jsFiddle
Upvotes: 2
Reputation: 2629
You can set the image's max-width: 100%; which would limit its size only if it's bigger than its parent.
img {
height: auto;
max-width: 100%;
}
Demo here: http://jsfiddle.net/LMEwC/
Upvotes: 16
Reputation: 190
Use JavaScript to find the respective width/height of picture and div and then resize the image to the fit the div.
You can use this code to find the height, create this function.
function getHeight(id)
{
return document.getElementById("id").offsetHeight; // Change to .offsetWidth to gain width :)
}
call the function like this:
function resize()
{
var imgHeight = getHeight("img");
var divHeight = getHeight("div");
//Then ask:
if(imgHeight > divHeight)
{
pic = document.getElementById("img");
pic.style.height = divHeight;
}
}
Now you need some action to call the functions, might work? or some onclick event? Depends on how you are using this image.
I hope this helps. It SHOULD do the job.
NB: It has come to my attention that used with spesific types of elements Google Chrome simply ignores max/min-width, when width is present (CSS)! But not always.
Upvotes: 0
Reputation: 10736
Add a min-width to the css.
img {
width:100%;
min-width:50px;
}
Upvotes: 0