977 B
977 B
title, type, language, tags, author, cover, dateModified
| title | type | language | tags | author | cover | dateModified | |
|---|---|---|---|---|---|---|---|
| Aspect ratio | snippet | css |
|
chalarangelo | digital-nomad-12 | 2022-08-14T05:00:00-04:00 |
Creates a responsive container with a specified aspect ratio.
- Use a CSS custom property,
--aspect-ratioto define the desired aspect ratio. - Set the container element to
position: relativeandheight: 0, calculating its height using thecalc()function and the--aspect-ratiocustom property. - Set the direct child of the container element to
position: absoluteand filling it parent, while giving itobject-fit: coverto maintain the aspect ratio.
<div class="container">
<img src="https://picsum.photos/id/119/800/450" />
</div>
.container {
--aspect-ratio: 16/9;
position: relative;
height: 0;
padding-bottom: calc(100% / (var(--aspect-ratio)));
}
.container > * {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}