Keep a 16:9 aspect ratio in CSS
10 Keep a box at a fixed aspect ratio
easyMake a box hold a shape, say 16 by 9, whatever width it is given. Use the modern property and note the trick it replaced.
Stuck? Three hints, smallest first
- 1.
aspect-ratio: 16 / 9is one line and does the whole job. - 2. The old way was a wrapper with
padding-top: 56.25%, which is 9 divided by 16. - 3. Only set one dimension. Set both and the ratio has nothing left to decide.
<div class="ratio">16 ÷ 9</div>
<div class="ratio square">1 ÷ 1</div>
.ratio {
width: 200px; /* set ONE dimension; the ratio decides the other */
aspect-ratio: 16 / 9;
display: grid;
place-items: center;
margin-bottom: 10px;
background: #3055d8;
color: #fff;
border-radius: 8px;
}
.ratio.square { aspect-ratio: 1 / 1; }
/* The old approach, for comparison. 9 / 16 = 56.25%, and percentage padding
is relative to the WIDTH, which is what made it work at all:
.old { padding-top: 56.25%; height: 0; } */
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// The comment at the bottom shows the OLD technique, so it mentions both
// padding-top and height. Strip comments before asserting about real rules,
// or the check fails on the very example it is explaining.
const rules = css.replace(/\/\*[\s\S]*?\*\//g, '');
test('the ratio is declared', /aspect-ratio\s*:\s*16\s*\/\s*9/.test(rules), true);
test('a square variant too', /aspect-ratio\s*:\s*1\s*\/\s*1/.test(rules), true);
test('only the width is set', /width\s*:\s*200px/.test(rules), true);
test('no explicit height fights the ratio', /[^-]height\s*:\s*\d/.test(rules), false);
test('the padding hack is not needed', /padding-top\s*:\s*56\.25%/.test(rules), false);
test('but it is still shown in a comment, for recognition', /56\.25%/.test(css), true);
test('place-items centres the label in one line', declares(css, 'place-items', 'center'), true);
test('two boxes', countTag(html, 'div'), 2);
Output
aspect-ratio replaced a genuinely strange hack: a wrapper with zero height and padding-top: 56.25%, which worked only because percentage padding resolves against the element's width. Worth knowing the old form because you will still meet it. The fourth assertion matters: setting an explicit height as well leaves aspect-ratio nothing to compute, so it silently does nothing.