如果您的目标是支持 CSS3 的现代浏览器,您可以尝试以下方法。
考虑以下 HTML sn-p:
<div class="wrapper">
<div class="inner">Inner content...</div>
</div>
并应用以下 CSS 规则:
html, body {
height: 100%;
}
body {
margin: 0;
}
.wrapper {
background-color: lightblue;
height: 100%;
}
.wrapper .inner {
margin: 0 auto;
background-color: beige;
height: 100%;
width: 66.6666666666vh;
}
.wrapper 元素占据了视口高度的 100%,因为我已经设置了
height: 100% 在 body 和 html 元素上。
内部包装器.inner 有一个height: 100% 并填充父块。
要设置.inner 宽度,请使用视口百分比长度vh,它会随父块的高度缩放。
在本例中,66.66vh 表示垂直高度的 66.66%,对应于 2:3 纵横比(宽:高)。
在 jsFiddle
上查看演示
参考:http://www.w3.org/TR/css3-values/#viewport-relative-lengths
浏览器兼容性
vh 单位和其他垂直百分比长度在最新的浏览器中得到了很好的支持,更多详细信息请参见下面的参考。
见参考:
https://developer.mozilla.org/en-US/docs/Web/CSS/length#Browser_compatibility
使用间隔图像的替代方法
考虑以下 HTML:
<div class="ratio-wrapper">
<img class="spacer" src="http://placehold.it/20x30">
<div class="content">Some content...</div>
</div>
并应用以下 CSS:
.ratio-wrapper {
position: relative;
display: inline-block;
border: 1px solid gray;
height: 500px; /* set the height or inherit from the parent container */
}
.ratio-wrapper .spacer {
height: 100%; /* set height: 100% for portrait style content */
visibility: hidden;
vertical-align: top;
}
.ratio-wrapper .content {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
padding: 20px;
}
.ratio-wrapper 容器有两个子元素,img.spacer 和 div.content。
图像为纵向纵横比,例如 20x30 (wxh),并使用height: 100% 设置为展开以填充父容器的高度。图像在视图中隐藏,但在父块中保留其空间。
.content 元素绝对定位以填充父容器,并且可以包含任何内容。因为.content的高度和宽度有限制,在某些情况下内容可能会溢出,所以设置overflow: auto可能比较合适。
查看演示:http://jsfiddle.net/audetwebdesign/BVkuW/
相关问答:
In Fluid Container, Can I Make Elements as Tall as they Are Wide?