Setting Element Width Based on Height Via CSS
I have a set of elements and require that their minimum width be equal to their height, but the height is not explicitly set. Currently I am able to achieve this by setting the css min-width
property via jQuery:
$(document).ready
(
function()
{
$('.myClass').each
(
function() {$(this).css('min-width', $(this).css('height'));}
);
}
);
Is it possible to specify this behaviour directly in the css?
Here is a jsfiddle demonstrating what I am trying to achieve: http://jsfiddle.net/p8PeW/
Solution 1:
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.
Solution 2:
Now the new aspect-ratio
property can easily do this and it work in both situation:
- Height based on width
- Width based on height
We simply set the ratio and either the width or the height:
.box {
height:80vh;
background:red;
aspect-ratio:9/6;
}
.box1 {
width:50vw;
background:green;
aspect-ratio:9/6;
}
<div class="box">
</div>
<div class="box1">
</div>