CSS & HTML Video Tutorial: Make Your Videos Responsive


When integrating videos (via iframe or the video tag) we often want the element to respect a predefined ratio whatever the width of the element. We will see the different methods that can be used to solve this problem.

CSS property aspect-ratio

The property aspect-ratio is still in the draft stage and is little supported, but it offers a simple solution.

.video {
  aspect-ratio: 16/9;
  width: 100%;
  height: auto;
}

Thus, the element will automatically take a height according to the defined ratio. However, it is important to note that the ratio can be overridden if you force a certain height.
For example a max-height will outweigh the ratio:

.video {
  aspect-ratio: 16/9;
  width: 100%;
  height: auto;
  max-height: 350px;
}

Also, if the content exceeds in height, the height of the element will be adapted to avoid overflow.

The padding-bottom in %

While waiting for property support aspect-ratio alternative methods can be used to achieve a similar result. An interesting property of the padding is that if the unit is in percentage the calculation is done in relation to the width of the container.

percentage: The size of the padding as a percentage, relative to the width of the containing block. Must be negative.

We can therefore use this specificity to obtain a height based on the width.

.ratio {
    position: relative;
}
.ratio :: before {
    happy:'';
    display: block;
    / * ratio of 16/9 * /
    padding-bottom: 56.25%;
}
.ratio> * {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}

We can also use CSS variables to make things dynamic

.ratio :: before {
  padding-bottom: calc (100% / (var (- ratio, calc (16/9))));
}

This makes it possible to control the ratio via a simple property.