This is actually possible without JS!
The key is to make use of an <img>
, which is a replaced element, and hence if you only set the height, it's width will be automatically set in order to preserve the intrinsic aspect ratio of the image.
Hence you can do the following:
<style>
.container {
position: relative;
display: inline-block; /* shrink wrap */
height: 50vh; /* arbitrary input height; adjust this */
}
.container > img {
height: 100%; /* make the img's width 100% of the height of .container */
}
.contents {
/* match size of .container, without influencing it */
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
<div class="container">
<!-- transparent image with 1:1 intrinsic aspect ratio -->
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
<div class="contents">
Put contents here.
</div>
</div>
If you wanted .contents
to have a 4:3 aspect ratio, then you would instead set the height of the img to 133%, so the width of the img and hence of .contents
would be 133% of the height of .container
.
Live demo of 1:4 aspect ratio: https://jsbin.com/juduheq/edit (with additional code comments).
Another live demo, where the height of the container is determined by the amount of text in a sibling element: https://jsbin.com/koyuxuh/edit
In case you're wondering, the img data URI is for a 1x1 px transparent gif). If the image didn't have a 1:1 aspect ratio, you'd have to adjust the height values you set correspondingly. You could also use a <canvas>
or <svg>
element instead of the <img>
(thanks Simo).
If instead you want to set element height based on width, there's a much easier trick at Maintain the aspect ratio of a div with CSS.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…