使用填充技巧以响应方式缩放元素并保持设定的纵横比。但是,当高度来自填充时,如何设置最大高度?
参见示例,我希望它可以缩放,但是一旦它达到设定的高度,高度就不会缩放(但会保持全宽)。
#container {
background-color: #666;
color: #ccc;
padding-top: 23%;
height: 0;
overflow: hidden;
}
最佳答案
如果你的容器需要整页,就像你的 fiddle 一样,你可以使用 height: 23vw
而不是 padding: 23%
.通过这样做,您还可以设置最大高度:
#container {
background-color: #666;
color: #ccc;
height: 23vw;
max-height: 200px;
overflow: hidden;
}
#container .inner {
position: absolute;
top: 20px;
left: 20px;
right: 20px;
z-index: 1;
font-size: 11px;
}
<div id="container">
<div class="inner">This div should scale with the browser, and maintain the same aspect ratio.</div>
</div>
当然,如果元素不那么宽,但是你知道公式,你可以调整宽度。例如,如果您希望它占页面宽度的 50%,则可以将高度设置为:calc(23vw * 0.5)
, 或者只是 11.5vw
.
PS:如果你想将内部元素定位在外部,确保添加 position: relative
到外部元素。这将使内部元素的顶部、左侧、右侧和底部相对于外部元素的边界。
关于css - 灵活的 DIV 保持宽高比,但如何拥有最大高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734257/