使一个元素的宽度相对于其高度而定?

11

我知道可以通过百分比的 margin 和 padding 值相对于宽度来指定元素的高度,例如:指定元素高度与宽度的比例。那么反过来,是否能够实现高度相对于宽度的比例?

1个回答

9

我找到了一种不需要使用Javascript的方法。制作一个按比例缩放的图片,并将其嵌入HTML中,根据比例缩放它,这样父元素就能够inline-block地适应图片尺寸。

<!-- height of the outer container -->
<div style="height: 200px">

    <!-- this will resize to 200px and maintain its aspect ratio --->
    <div style="display: inline-block; position: relative;">
        <img src="aspectratio.png" style="height: 100%; width: auto;" />
        <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0">
            <!-- Everything in here can party on the fact that their parent
                 has the correct aspect ratio -->
        </div>
    </div>

</div>

能否裁剪图像并以任意宽高比生成图像? - mulllhausen
1
@mulllhausen,你可以使用visibility: hidden的http://placekitten.com/图片。 - Brilliand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接