<h1>The Ratio Object</h1> <div class="box o-ratio"> <p class="o-ratio__content">1:1</p> </div> <h2>Different aspect ratios</h2> <div class="box o-ratio o-ratio--4:3"> <p class="o-ratio__content">4:3</p> </div> <div class="box o-ratio o-ratio--16:9"> <p class="o-ratio__content">16:9</p> </div>
/* ========================================================================== #RATIO OBJECT ========================================================================== */ /** * The ratio object creates an element that is constrained to a certain aspect * ratio while allowing it to expand to the full width. * * 1. The default ratio is 1:1 (perfect square). * 2. Allow space for additional UI. */ .o-ratio { --o-ratio-width: 1; /* [1] */ --o-ratio-height: 1; /* [1] */ --o-ratio-ui-height: 0; /* [2] */ display: block; position: relative; } .o-ratio::before { content: ""; display: block; padding-bottom: var(--o-ratio-ui-height); padding-top: calc((var(--o-ratio-height) / var(--o-ratio-width)) * 100%); width: 100%; } .o-ratio__content { bottom: 0; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } .o-ratio--4\:3 { --o-ratio-width: 4; --o-ratio-height: 3; } .o-ratio--16\:9 { --o-ratio-width: 16; --o-ratio-height: 9; } /* ========================================================================== #PAGE STYLES ========================================================================== */ p { background-color: pink; margin: 0; } .box { border: 1px solid #000; margin-bottom: 1em; width: 10em; }