I saw solution for height depending on width: css height same as width. Or here: https://stackoverflow.com/a/6615994/2256981. But my question is opposite.
My element:
<body>
<div id="square"></div>
</body>
Style for it:
body, html {
margin: 0;
height: 100%;
min-height: 300px;
position: relative;
}
div#square { /* My square. */
height: 75%; /* It's height depends on ancestor's height. */
width: 75vh; /* If supported, preliminarily sets it's width. */
position: absolute; /* Centers it. */
left: 50%; top: 50%; transform: translate(-50%, -50%);
background-color: darkorange; /* Makes it visible. */
}
Script, that keeps it square:
window.onload = window.onresize = function (event) {
var mySquare = document.getElementById("square");
mySquare.style.width = mySquare.offsetHeight + 'px';
};
Complete code here: http://jsfiddle.net/je1h/hxkgfr9g/
The question is to make the same thing in pure CSS. No scripting.
Edit: Missed that you wanted to set the width depending of the height, this does the opposite :(
To support all ratios you can use
padding-bottom
. Percentages in padding-bottom are always relative to the width of the element:The only downside is, that you need a bunch of wrapper elements.
There are two techiques I am aware of to keep the aspect ratio of an element according to it's height :
When height is relative to the viewport :
You can use vh units :
For a height based on the height of a parent element :
You can use a dummy image that has the aspect ratio you want. Example with a 1:1 aspect ratio you can use a 1*1 transparent .png image or as commented by @vlgalik a 1*1 base64 encoded gif :
Note that this last demo doesn't update on window resize. But the aspect ratio is kept on page load
UPDATE :
As reported in the comments setting
display:inline-flex:
on#el
seems to solve the updating on window resize problem.