Responsive Youtube / Vimeo Embeds with CSS

css
Published on February 28, 2021

Youtube or Vimeo video embeds are basically iframes, so they need a height to be provided explicitly. This becomes a problem while maintaining responsiveness for various screen sizes.

However with a bit of CSS, Youtube / Vimeo iframes can be laid out in a specified aspect ratio. Once aspect ratio of the iframe is set, height will be automatically calculated and the videos will be responsive.

  • A box can be created of a specified aspect ratio by doing some markup changes and using CSS padding property.
  • For latest browsers, CSS aspect-ratio property can be used to create a box of a given aspect ratio.

Method 1 : Using CSS padding

Note: When padding is used as a percentage, it is calculated on the width of the parent element.

This method is more of a hackish way to create a box of a given aspect ratio. Some HTML changes may be required.

Now Youtube or Vimeo videos are usually of 16:9 or 4:3 aspect ratio.

  • 16:9 means height is 9/16 times the width, or 0.5625 or 56.25%
  • 4:3 means height is 3/4 times the width, or 0.75 or 75%

To embed a video in 16:9 aspect ratio, the required HTML & CSS needs to be something like :

<div class="video-outer">
 	<div class="video-inner">
 		<iframe class="video" src="https://www.youtube.com/embed/8aGhZQkoFbQ"></iframe>
 	</div>
</div>
/* sets width, can be changed as per need */
.video-outer {
	width: 100%;
}

/* padding-top sets the overall height */
.video-inner {
    padding-top: 56.25%;
    height: 0px;
    position: relative;
}

/* final iframe uses 100% width & height */
.video {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

If a box of 4:3 aspect ratio is required, padding-top: 75% can be set, rest will be the same.

See demo

Method 2 : Using CSS aspect-ratio

The CSS aspect-ratio property is a direct way to create box of a specified aspect ratio, without doing any HTML changes.

This method should be preferred as implementing this is very easy. However aspect-ratio is a new CSS property, and is currently supported only in Chrome & Edge.

aspect-ratio is directly specified as a ratio of width / height.

To embed a video in 16:9 aspect ratio, the required HTML & CSS needs to be something like :

<iframe class="video" src="https://www.youtube.com/embed/8aGhZQkoFbQ"></iframe>
/* sets width, can be changed as per need */
video {
	width: 100%;
	aspect-ratio: 16/9;
}

If a box of 4:3 aspect ratio is required, aspect-ratio: 4/3 can be set, rest will be the same.

See demo

In this Tutorial
    Comments
    Loading Comments