css 灵活的DIV保持纵横比,但如何有最大高度?

c9x0cxw0  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(113)

使用填充技巧以响应方式缩放元素并保持设置的纵横比。但是,当高度来自填充时,如何设置max-height?
见例子,我想这规模,但一旦它的命中设置高度,然后高度不规模(但保留全宽)。

#container {
    background-color: #666;
    color: #ccc;
    padding-top: 23%;
    height: 0;
    overflow: hidden;
}

http://jsfiddle.net/louiswalch/9h4c8tor/

kmbjn2e3

kmbjn2e31#

如果你的容器需要整个页面的宽度,就像你的小提琴一样,你可以使用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添加到外部元素。这将使内部元素的顶部、左侧、右侧和底部相对于外部元素的边界。

mspsb9vt

mspsb9vt2#

不能使用填充技巧独立于宽度限制高度。但是,你可以伪造它。
你可以计算出你想要限制元素高度的宽度,然后将元素 Package 在一个容器中,并将该容器的最大宽度设置为指定的宽度并将其居中。
然后,为了允许背景继续穿过, Package 容器并将背景颜色应用于 Package 。
Demo

body {
    margin: 0;
}
.wrp-bg {
    background-color: #666;
}
.wrp {
    max-width: 800px;
    margin: 0 auto;
}
#container {
    padding-top: 23%;
    position: relative;
}
#container .inner {
    color: #ccc;
    position: absolute;
    top: 0;
    width: 100%;
    bottom: 0;
    padding: 20px;
    font-size: 11px;
    box-sizing: border-box;
}
<div class="wrp-bg">
    <div class="wrp">
        <div id="container">
            <div class="inner">This div should scale with the browser, and maintain the same aspect ratio.</div>
        </div>
    </div>
</div>

相关问题