Div具有100%的高度和特定的宽高比

And*_* Ka 6 css html5 css3

我怎样才能拥有100%高度的div具有特定的宽高比,例如2:3?

例如,如果外部元素的高度为900px,则内部元素的宽度应为600px,但这应该是响应性的.

我不想为此使用任何JavaScript.

使用CSS3灵活的盒子模型会很好.

Mar*_*det 7

如果您的目标是支持CSS3的现代浏览器,则可以尝试以下操作.

请考虑以下HTML代码段:

<div class="wrapper">
    <div class="inner">Inner content...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

并应用以下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;
}
Run Code Online (Sandbox Code Playgroud)

.wrapper元素占据了视图端口高度的100%,因为我已经设置 height: 100%bodyhtml元素.

内包装.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>
Run Code Online (Sandbox Code Playgroud)

并应用以下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;
}
Run Code Online (Sandbox Code Playgroud)

.ratio-wrapper容器有两个子元素,一个img.spacerdiv.content.图像为纵向纵横比,例如20x30(wxh),并设置为展开以填充父容器的高度height: 100%.图像在视图中隐藏,但在父块中保留其空间.

.content元素绝对定位为填充父容器,并且可以包含任何内容.由于.content高度和宽度受限制,在某些情况下内容可能会溢出,因此设置overflow: auto可能是合适的.

请参阅演示:http://jsfiddle.net/audetwebdesign/BVkuW/

相关问答:
在流体容器中,我可以使元素像它们一样宽吗?