Responsive YouTube video embedding

How to embed YouTube videos in your website and make them responsive to scale down on mobile devices

The problem with embedding YouTube videos is that they areiframeAnd need to give the iframe precise height and width, otherwise they will look very fashionable.

Moreover, we need to maintain the ratio based on the video aspect ratio.

To make a YouTube video appear responsive on your page, first wrap it in a container div:

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/klZNNUz4wPQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

Then add this CSS to your site:

.video-container {
    overflow: hidden;
    position: relative;
    width:100%;
}

.video-container::after { padding-top: 56.25%; display: block; content: ‘’; }

.video-container iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

See thatMagic number,56.25%? When the aspect ratio of the video is 16:9, this needs to be filled. (9 is 56.25% of 16).

For example, if your video is 4:3, set it to 75%.

Download mine for freeCSS Manual


More CSS tutorials: