Embed YouTube video and make it look responsive: two solutions with CSS and JavaScript

YouTube is a powerful tool for watching online videos of all kinds, both for leisure and professionally, and it adapts perfectly to many other niches such as blogging; YouTube allows us to easily insert videos into our website, but what may not be so easy is for the video to behave in a responsive manner; which means that the video adapts to the web, to the size of the web that depends on the size of the screen and in this way we can easily incorporate YouTube videos on our website as we saw in a previous post and that they are responsive

When we embed the video code on our website and test it on a phone or tablet, the result is quite unpleasant... we see that YouTube does not re-scale the video correctly according to the size of the screen; If we analyze the video we see that it has a fixed size defined by the height and width attributes.

Therefore, the code that YouTube gives us already has a predefined size indicating its width and length and ignores the fact that the content is responsive.

When we try to make a responsive YouTube video we see that it gives us many problems, when trying to scale the video, make it look correctly and we cannot make the video responsive on mobile phones, tablets and PCs; But don't worry, we bring a couple of solutions which you can use one or the other depending on your needs.

How to make a responsive YouTube video

For this topic, how to make our videos look as God intended, without cutting and can be consumed or viewed correctly, we present two solutions, one of them is through CSS and a little more general and the other is through JavaScript which is more complete and allows videos to be adapted correctly according to the proportions of the video.

You can use them together or individually and experiment as you wish so that your videos look the way you want; the first one we will see will be with CSS.

First responsive option for video with CSS

Previously we talked about how to place a In this video we will see how to make a responsive YouTube video so that it looks correctly; as we indicated later, we need a container to place the iframe that contains the video; for that we can apply CSS like the following:

.v-container {
	position: relative;
	padding-bottom: 56.25%; /* proporción 16:9 */
	padding-top: 25px;
	height: 0;
}

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

The CSS above allows the container to have a fixed space provided by the padding-bottom in order to scale the video according to the proportions of the window; then we indicate the maximum size of our video both in width and height (and here the padding-bottom that we indicated above comes into play, which allows us to control the height of the iframe of the YouTube video) and in this way we obtain our video adaptable to the screen of your phone, PC, tablet or any other device.

Defining the HTML of our YouTube video

You can remove (or not) the attributes that YouTube adds when exporting the video to define the fixed height and width; that is to say; if this is our video:

<iframe width="560" height="315"   src="https://www.youtube.com/embed/Me2aXBodqnA" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> 

It would look like this:

<iframe src="https://www.youtube.com/embed/Me2aXBodqnA" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> 

And this is the result:

video adaptativo con CSS

You can consult the example at:

Example

Second responsive option for the video with JavaScript

Although the one presented above with CSS is not a foolproof solution and can cause us some problems depending on the proportions or dimensions of the videos that we are going to attach; However, it is a quick way that we have to make our YouTube videos adaptive without many problems but it is a little more elaborate and requires JavaScript with which we can adapt the YouTube video shown based on its proportion and make it scalable, adaptive or responsive.

To do this, the first thing we have to do is obtain all the YouTube videos; which we can easily do with the following JavaScript; the first thing we do is select all the videos whose src attribute contains the YouTube URL; for that we use the containment selector *:

var $videosYoutube = $("iframe[src*='www.youtube.com']")

Here we use jQuery, but you can easily translate the code to native JavaScript if not using jQuery; the next thing we do is select the direct parent container of our video, in the example presented in this entry, it would be a section, but you put yours:

$v_container = $("body section")

Next step, we calculate the proportions, the radius aspect, or whatever you want to call it from the group of YouTube videos obtained and we save it in an attr that we define; this code is only executed once when the website loads, for this the following code is used:

$videosYoutube.each(function () {
	$(this)
			.attr('proportion', this.height / this.width)
			//removemos las dimenciones del video
			.removeAttr('height')
			.removeAttr('width');

The next step is to define the callback for when the window is resized and apply the rescaling of our video:

$(window).resize(function () {
	$videosYoutube.each(function () {

		var $el = $(this);
		$el
				.width(container_width)
				.height(container_width * $el.attr('proportion'));

	});
})

This method is executed every time the window or web page is rescaled and therefore rescales the video to make it adaptive as the container size varies.

Finally the code to make our videos responsive on YouTube:

// Find all YouTube videos
var $videosYoutube = $("iframe[src*='www.youtube.com']"),
		// el padre contenedor
		$v_container = $("body section");

// iteramos todos los videos de youtube y guardamos sus proporciones
$videosYoutube.each(function () {
	$(this)
			.attr('proportion', this.height / this.width)
			//removemos las dimenciones del video
			.removeAttr('height')
			.removeAttr('width');

});

// Cuando se redimenciona la ventana
$(window).resize(function () {

	var container_width = $v_container.width();

	// Resize all videos according to their own aspect ratio
	$videosYoutube.each(function () {

		var $el = $(this);
		$el
				.width(container_width)
				.height(container_width * $el.attr('proportion'));

	});
}).resize(); // invocamos el método a la carga

You can see the final example in the following link:

Examples

You can use these codes with other video systems such as Vime so that the videos also adapt to the size of the screen; they work perfectly to make our videos responsive once and for all.

Examples

- Andrés Cruz

En español
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.