YouTube

Making YouTube videos scale in all browsers, tablets and phones for responsive design

To scale a YouTube video to fit any browser or tablet/mobile device for responsive design you can use either a CSS or Javascript solution to accomplish the goal.

This example uses a CSS solution, you need to add a couple of CSS styles in your main CSS file.

The Process

The first thing that you need is the YouTube iframe embed code, grab that in your video share options from the YouTube site.

Place the iframe code on your page, in this example above the iframe's container div (div.youtubevideowrap) has 2 CSS declarations for width, it has a width:80% and a max-width:640px.

This makes the content fluid as a percentage unit is used, it also has a max-width set as I don't want the video displaying wider than 640px

From here we need to add in a HTML container around the video and declare the CSS.

Setting Up the HTML and CSS Styles

Create a container div around the iframe code and give it a class eg:

<div class="video-container"><iframe.......></iframe></div>

Add in the CSS:

.video-container {
	position:relative;
	padding-bottom:56.25%;
	padding-top:30px;
	height:0;
	overflow:hidden;
}

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

The first CSS declarations target the video container and the second target what is in the container, in this case it's the iframe, you can also apply this to objects and embed elements.

That's it the video will now scale as the viewport is resized, the magic element is the padding-bottom rule of 56.25%, this figure is reached by using the video's aspect ratio of 16*9, so 9 divided by 16 = 0.5625 or 56.25%, full explanation in alistapart article.

This same process can also be achieved using a javascript technique explained in the Vimeo video guide, which plays just as friendly with YouTube videos.

comments powered by Disqus