The problem
You need containers or media elements to maintain a consistent aspect ratio across different screen sizes.
The solution
/* Modern aspect-ratio property */
.ratio-16-9 {
aspect-ratio: 16 / 9;
width: 100%;
object-fit: cover;
}
.ratio-4-3 {
aspect-ratio: 4 / 3;
}
.ratio-1-1 {
aspect-ratio: 1 / 1; /* Square */
}
/* For images */
.responsive-img {
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
object-fit: cover;
border-radius: 8px;
}
/* Legacy padding-bottom trick */
.ratio-box-legacy {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 = 9/16 = 0.5625 */
}
.ratio-box-legacy > * {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}See it live
Put it to work
<div class="ratio-16-9">
<img src="thumbnail.jpg" alt="Video thumbnail">
</div>
<video class="ratio-16-9" controls>
<source src="video.mp4" type="video/mp4">
</video>Worth knowing
The aspect-ratio property is widely supported. Use the padding-bottom trick only for older browser support.