是否有一种 css 方式可以将任何图像放入容器中? (节省比例)
如果图像小于容器,min-width/-height
会完成这项工作。如果图像更大,则 max-width/-height
。
那么适合任何更小/更大图像的方法是什么?显然它不是最小值/最大值。
应该在 IE11 中工作
<div style='width:20vh; height:20vh; text-align:center'>
<img style='width:auto; height:auto; max-width:100%; max-height:100%; display:inline' src='...' />
</div>
最佳答案
如果背景图像是可以接受的,那么使用 background-size: contain;背景位置:中心;保持居中并保存纵横比。请参阅下面的片段。它也适用于 IE11。
.image {
width: 300px;
height: 300px;
background-image: url('https://images.unsplash.com/photo-1563927648995-79a6ffffc028?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60');
background-size: contain;
background-position: center;
background-repeat: no-repeat;
background-color: gray;
}
<div class="image"></div>
关于CSS 使图像适合容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57181270/