Here's a CSS trick also known as "the padding hack" to set the aspect ratio of an element!
Image Ratio in 16/9Image Ratio in 4/3
HTML
<div class="aspect-ratio" > <img src="https://picsum.photos/1080/720" alt=""> </div> <div class="aspect-ratio fourthree" > <img src="https://picsum.photos/1080/720" alt=""> </div>
CSS
.aspect-ratio { --aspect-ratio: 16/9; position: relative; height: 0; padding-bottom: calc(100%/(var(--aspect-ratio))); } .aspect-ratio.fourthree { --aspect-ratio: 4/3; } .aspect-ratio > * { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; }
Comments
Post a Comment