我有以下反复出现的问题,我无法找到有效的解决方案。其他人必须遇到同样的问题,但尽管搜索我似乎无法找到确切的问题,尽管它必须是非常普遍的。希望这个问题对许多开发人员有用。
我的目标是填充容器div中的图像并使其居中。图像可以是纵向,横向或正方形,并且具有可变的不同纵横比/尺寸。容器div具有固定高度但基于百分比的宽度,因此也是可变的。
我发现使用下面的代码,图像被缩放得非常大,并且对代码的任何调整都会导致纵横比的拉伸,这是不可取的。当然,裁剪是不可避免的,但我想找到最小化这种方法的最佳方法,并尽可能以最好的方式显示所有图像。我在容器div中添加了一个红色背景,因为我不想在任何实例中显示任何内容。
我对可能存在的任何决议持开放态度。
Fiddle(按比例浏览浏览器)
HTML
<div class="container">
<img src="http://lorempixel.com/1000/500/">
</div>
<div class="container">
<img src="http://lorempixel.com/500/1000/">
</div>
<div class="container">
<img src="http://lorempixel.com/500/500/">
</div>
CSS
.container {
width: 40%;
height: 350px;
display: inline-block;
float: left;
background: red;
overflow: hidden;
margin: 10px;
}
.container img {
display: block;
width: auto;
min-width: 100%;
height: auto;
min-height: 100%;
}