Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make images scale to parent div only when larger, all while using an explicit max-width

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?

like image 408
Chris Redford Avatar asked Aug 07 '13 20:08

Chris Redford


People also ask

How to resize images with the CSS max-width property?

Resize images with the CSS max-width property ¶ There is a better way for resizing images responsively. If the max-width property is set to 100%, the image will scale down if it has to, but never scale up to be larger than its original size. The trick is to use height: auto; to override any already present height attribute on the image.

How to make the image responsive with a maximum width?

If you want to make the image responsive with a maximum width then you have to define both width and maximum-width on the img element. E.G., img { width: 100%; maximum-width: 330px } No you don't need both. you only need max-width and the image will grow to its natural width as max. Look at this jsfiddle. Is that what you are looking for?

How to limit the size of image to the parent element?

You can set the image's max-width: 100%; which would limit its size only if it's bigger than its parent. Show activity on this post. In case you are using Bootstrap (version 3.x, perhaps other versions as well) you can also use on your <img> tag to resize it to the parent element's size. Show activity on this post. Show activity on this post.

How to scale an image to 100% of its parent element?

Start to make the browser window narrower and watch the bottom image scale and top one remain the same size. The bottom one is scaling to 100% of its parent element which will change depending on the width of the viewport in a responsive design.


1 Answers

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

like image 63
Simone Conti Avatar answered Jan 02 '23 02:01

Simone Conti