尝试针对以下问题获取仅限CSS 解决方案。
我想在容器中显示各种大小的图像。如果图像大于80%视口高度,则应按比例缩小以适合容器。
我遇到的问题是缩放到最大高度和最大宽度(为了适应横向和纵向图像)。
这是一个不起作用的JSFiddle作为起点。没有图像应该流出灰色框。 https://jsfiddle.net/0h5zkk0z/2/
<div id="container">
<img src="http://dummyimage.com/200x200/000/fff/?text=small" />
</div>
<div id="container">
<img src="http://dummyimage.com/400x700/000/fff/?text=portrait" />
</div>
<div id="container">
<img src="http://dummyimage.com/600x400/000/fff/?text=landscape" />
</div>
<style>
#container {
max-height: 80vh;
background-color: #ccc;
position: relative;
margin-bottom: 30px;
}
#container IMG {
margin: 0 auto;
display: block;
width: auto;
height: 100%;
}
</style>
答案 0 :(得分:0)
.container {
max-height: 80vh;
background-color: #ccc;
position: relative;
margin-bottom: 30px;
}
.container img {
margin: 0 auto;
display: block;
width: auto;
max-height: inherit; //Inherits from container height
}
顺便说一下:请仅使用一次ID: - )