CSS: using aspect ratio
Inspired by https://twitter.com/ryanseddon/status/1026321377228349440
by Julien Roche
HTML
<h1>Natural ratio</h1>
<img src="https://images.pexels.com/photos/289225/pexels-photo-289225.jpeg?auto=compress&cs=tinysrgb&h=650&w=940" />
<br />
<br />
<h1>16/9 ratio</h1>
<img class="ratio-image-16-9" src="https://images.pexels.com/photos/289225/pexels-photo-289225.jpeg?auto=compress&cs=tinysrgb&h=650&w=940" />
<br />
<br />
<h1>21/9 ratio</h1>
<img class="ratio-image-21-9" src="https://images.pexels.com/photos/289225/pexels-photo-289225.jpeg?auto=compress&cs=tinysrgb&h=650&w=940" />
<br />
<br />
<h1>4/3 ratio</h1>
<img class="ratio-image-4-3" src="https://images.pexels.com/photos/289225/pexels-photo-289225.jpeg?auto=compress&cs=tinysrgb&h=650&w=940" />
CSS
:root {
--ratio-width: 100vw;
--ratio-height-16-9: calc(var(--ratio-width) * 9 / 16);
--ratio-height-21-9: calc(var(--ratio-width) * 9 / 21);
--ratio-height-4-3: calc(var(--ratio-width) * 3 / 4);
}
html,
body {
border: none;
height: 100%;
margin: 0 0 0 0;
padding: 0 0 0 0;
width: 100%;
}
.ratio-image-21-9 {
height: var(--ratio-height-21-9);
width: var(--ratio-width);
}
.ratio-image-16-9 {
height: var(--ratio-height-16-9);
width: var(--ratio-width);
}
.ratio-image-4-3 {
height: var(--ratio-height-4-3);
width: var(--ratio-width);
}