因此,可以在可变宽度和高度容器Codepen内居中和缩放未知尺寸的图像:
html,
body {
width: 100%;
height: 100%;
}
.Wrapper {
width: 50%;
height: 100%;
text-align: center;
font-size: 0;
vertical-align: middle;
}
.Wrapper:before {
content: '';
height: 100%;
vertical-align: middle;
display: inline-block;
}
.Wrapper--landscape {
float: right;
background: #DDD;
}
.Wrapper--portrait {
background: #AAA;
}
img {
max-width: 100%;
max-height: 100%;
display: inline-block;
vertical-align: middle;
}

<div class="Wrapper Wrapper--landscape">
<img src="https://dl.dropboxusercontent.com/u/316978/landscape.jpg">
</div>
<div class="Wrapper Wrapper--portrait">
<img src="https://dl.dropboxusercontent.com/u/316978/portrait.jpg">
</div>
&#13;
可以创建一个具有固定宽高比的流体宽度容器[Codepen(http://codepen.io/Pedr/pen/rVoyoL):
html,
body {
width: 100%;
height: 100%;
}
.Wrapper {
width: 50%;
height: 100%;
}
.Wrapper--left {
float: left;
}
.Wrapper--left {
float: right;
}
.AspectRatioBox {
width: 100%;
text-align: center;
font-size: 40px;
}
.AspectRatioBox--6-4 {
width: 100%;
padding-bottom: 66.666666%;
background: #CCC;
}
.AspectRatioBox--6-4::after {
content: '6:4';
}
.AspectRatioBox--16-9 {
width: 100%;
padding-bottom: 56.25%;
background: #666;
}
.AspectRatioBox--16-9::after {
content: '16:9';
}
&#13;
<div class="Wrapper Wrapper--left">
<div class="AspectRatioBox AspectRatioBox--6-4"></div>
</div>
<div class="Wrapper Wrapper--right">
<div class="AspectRatioBox AspectRatioBox--16-9"></div>
</div>
&#13;
但有没有办法同时做两件事?结合上述两种方法的问题在于,给容器提供固有比率的方法包括使用衬垫来给容器提供视觉高度。对于第一种技术而言,这不会很好,因为容器的高度为max-height: 100%
,因此需要提供图像0
。
注意:我正在寻找适用于现代浏览器的仅限CSS的解决方案。
答案 0 :(得分:0)
看起来答案是肯定的 - 通过使用额外的容器为图像创建新的上下文:Codepen
html,
body {
width: 100%;
height: 100%;
}
.Wrapper {
width: 50%;
height: 100%;
}
.CenteringContainer {
text-align: center;
font-size: 0;
vertical-align: middle;
}
.CenteringContainer:before {
content: '';
height: 100%;
vertical-align: middle;
display: inline-block;
}
.Wrapper--landscape {
float: right;
background: #DDD;
}
.Wrapper--portrait {
background: #AAA;
}
.IntrinsicContainer {
position: relative;
width: 100%;
padding-bottom: 56.25%;
}
.IntrinsicContainer-context {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #333;
}
img {
max-width: 100%;
max-height: 100%;
display: inline-block;
vertical-align: middle;
}
&#13;
<div class="Wrapper Wrapper--landscape">
<div class="IntrinsicContainer">
<div class="IntrinsicContainer-context CenteringContainer">
<img src="https://dl.dropboxusercontent.com/u/316978/landscape.jpg">
</div>
</div>
</div>
<div class="Wrapper Wrapper--portrait">
<div class="IntrinsicContainer">
<div class="IntrinsicContainer-context CenteringContainer">
<img src="https://dl.dropboxusercontent.com/u/316978/portrait.jpg">
</div>
</div>
</div>
&#13;