jsFiddle Demo
div
{
width: 200px;
height: 200px;
overflow: hidden;
margin: 10px;
position: relative;
}
img {
position: absolute;
margin: auto;
min-height: 100%;
min-width: 100%;
/* For the following settings we set 100%, but it can be higher if needed
See the answer's update */
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
}
更新 – 改进
正如Salman A在评论中提到的,原始的解决方案有一个缺陷 – 如果img的高度或宽度(或两者)(至少)比包含div大3倍*,它不能很好地工作。
问题显示为here。
Salman也给了一个非常简单和优雅的解决方案。我们只需要更新img的位置坐标(上,左,下,右)来处理更高的百分比。以下修正与1000%一起使用,但当然可以根据您的需要进行调整。
修复显示为here。
*原因是,当我们将img的左右(或:顶部和底部)坐标设置为(包含div的)-100%时,img的总体允许宽度(或:height)可以最多包含div的宽度(或:height)的300%,因为它是div的宽度(或:height)和左右(或:top和bottom)坐标的总和。