使元素的宽度相对于其高度?

时间:2012-06-04 06:02:56

标签: css

我知道可以specify an element's height relative to its width,因为百分比边距和填充值是相对于宽度计算的。是否可以做相反的 - 相对于高度的宽度?

1 个答案:

答案 0 :(得分: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>