There is standard trick to make HTML block with given proportions:
<div id="containingBlock"> <div id="wrapper" style="position:relative; width:100%; height:0px; padding-bottom:56.25%;"> <div id="content" style="position:absolute; left:0; top:0; width:100%; height:100%"> ... </div> </div> </div>
Since padding is computed according to containing element width, it’s possible to use it along with width to get required proportions (16:9 in this example, 56.25% = 100% * 9 / 16). And content block is positioned absolutely to use the space taken by padding.
After learning about Custom Elements I decided to see if I can abstract the trick and turn it into something clean and reusable. So I could use it just like this:
<ratio-box ratio="16:9"> ... </ratio-box>
See the code and demo below. In addition, there is also a slightly improved HTML+CSS version.
Update: removed resize-down trick. It no longer works in Chromium-based browsers, it seems.
There is one possible issue with original code that I solved in mine. When you try to limit block size, its’ height still being calculated according to parent block and will be different from what you’d expect. Below is the scriptless solution — as close as you could get to original, while fixing that issue. It also illustrate how my ratio-box works inside.
Although it is not as self-contained (there is an additional level of supporting tags and you need to introduce css classes for used proportions), it has no compatibility issues.