How to dynamically scale images per height using pure CSS?

大兔子大兔子 提交于 2019-12-02 04:30:04

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;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!