HTML aspect ratio box using Custom Element

There is a 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%">

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 it could be used just like this:

<ratio-box ratio="16:9">

Custom Elements is quite recent feature in HTML, with version 0 available only in Chrome and version 1 just coming into play. It also requires JavaScript to work. So it is not practical to use yet, but still an interesting experiment.

See the code and demo below. In addition, there is also a slightly improved HTML+CSS version.

As a bonus, there is also a trick to make resizable block able to go down in size (become smaller than original size) with no JavaScript. (Found there, but it seems that padding is also important to reduce the chance of flicker.)

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.

comments powered by Disqus