How to dynamically scale images per height using p

2019-03-01 11:09发布

问题:

This one goes out to the CSS pros:

I wonder if it's possible to achieve a image scaling behavior like on this site using pure CSS?

Be aware that the images only start scaling if the height of the browser window changes, not its width. (Just saying because all info on the web I found is about the alteration of the width.)

The real sticking point seems to be the different threshold values: Landscape-shaped images just start scaling down if they have the same height as the already downscaled portrait-shaped images.

Any feedback on that matter is highly appreciated!

回答1:

You can do it with a combination of max-height, min-height, white-space and % height. The only negative is that each image has to have a class set to determine if it is vertical or horizontal.

http://jsfiddle.net/Rgp6h/

Example HTML:

<div>
    <img src="http://placekitten.com/200/300" class="vert"/>
    <img src="http://placekitten.com/500/200" class="horiz"/>
    <img src="http://placekitten.com/200/300" class="vert"/>
    <img src="http://placekitten.com/400/300" class="horiz"/>
    <img src="http://placekitten.com/200/300" class="vert"/>
</div>

CSS:

body,html{
    height: 100%;
}

div{
 white-space: nowrap;
    height: 100%;
}

img{
    min-height: 200px;
    height: 100%;
    vertical-align: top;
}

.horiz{
    max-height: 300px;
}

.vert{
    max-height: 500px;
}


回答2:

I think they are just using JavaScript to do that, but you can just use percentage based sizes, or media queries if necessary.

.coolImg {
    height: 50%;
}
@media all and (max-height: 600px) {
    .coolImg {
        height: 50%;
    }
}

If you share some code of how you attempted to do it, we could try and solve you solution more specifically.