简体   繁体   中英

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?

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/

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.

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

Add a min-width to the css.

img {
    width:100%;
    min-width:50px;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM