给定一个任意宽高比的div,最好的方法是放置和设置图像(也有任意宽高比),以便:
这是我们想要的结果:
标记
Should pillarbox
<div class="frame">
<img src="http://www.placekitten.com/200/300" />
</div>
Should letterbox
<div class="frame">
<img src="http://www.placekitten.com/300/200" />
</div>
CSS
.frame {
width: 200px;
height: 200px;
border: 2px solid black;
margin: 10px 0px 100px 0;
}
答案 0 :(得分:4)
你可以尝试这样的事情:updated fiddle
.frame {
width: 200px;
height: 200px;
border: 2px solid black;
margin: 10px 0px 100px 0;
position: relative; /* added */
}
img {
max-height: 100%;
max-width: 100%;
position: absolute;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
}
答案 1 :(得分:2)
.frame {
width: 400px;
height: 400px;
border: 2px solid black;
margin: 10px 0px 100px 0;
position: relative; /* added */
}
img {
max-height: 100%;
max-width: 100%;
position: absolute;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
}
使用javascript
var inscribe = function(img, frame) {
var imgRatio = img.width / img.height;
var frameRatio = frame.offsetWidth / frame.offsetHeight;
if (imgRatio > frameRatio) { // image is wider than frame; letterbox
img.style.width = '100%';
img.style.height = 'auto';
} else { // image is taller than frame; pillarbox
img.style.width = 'auto';
img.style.height = '100%';
}
}
可以满足所有要求。
答案 2 :(得分:1)
如果你能摆脱<img />
元素,你也可以通过背景图像实现这一点。
背景大小 上有一个名为 包含 的css属性,可以完成这项任务:
.background{
background-size: contain;
}
如果您希望将图像居中,只需添加:
background-position: center center;