Make your images/ video responsive with aspect-ratio.
Aspect Ratio
Every object fit into a box. The box has a width and height. The aspect-ratio CSS property sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions.
Three ways to use aspect-ratio
aspect-ratio: <ratio>; /*`<ratio>` is a floating-point number followed by a unit.*/
aspect-ratio: <width> / <height>; /*`<width>` and `<height>` are floating-point numbers followed by a unit.*/
aspect-ratio: auto; /*The aspect ratio is determined by the intrinsic aspect ratio of the box’s contents.*/
Most common aspect-ratio
- 1/1 - Square
- 16/9 - Video
- 2 / 1 - Width is twice the height
- 1 / 2 - Height is twice the width
- 4 / 3 - Old TV
Example
aspect-ratio: 16 / 9;
Grid
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
.grid-container > * {
aspect-ratio: 16 / 9;
}
Flexbox
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1rem;
}
.flex-item {
flex: 0 0 calc(33.33% - 1rem);
aspect-ratio: 1 / 1;
overflow: hidden;
border: 1px solid #ddd;
}
.flex-item img {
width: 100%;
height: 100%;
object-fit: cover;
}