Embedding videos a different way

I’m starting a new project for a client over the coming weeks and one of the things I want to do during the project is make some improvements to the templates we use as the basis for most of our work.

One of the things that I really wanted to change is the way we deal with embedding videos. I was looking to get rid of the dependency on JavaScript (SwfObject). But in order to do that I’d have to solve two problems first.

The three reasons we started using SwfObject at work in the first place were:

  • You used to have to ‘click to activate’ Flash videos in our good friend IE. Luckily this is no longer an issue.
  • It allowed you to pass w3c validation. Now, I do not care if a page does not validate because of an embedded YouTube video, but our clients do, and they pay the bills.
  • We wanted to be able to size the embedded content to fit the page layout. We could use JavaScript to calculate the dimensions before we injected it into the document.

Embedding without <embed>

So the first thing we’d need is the HTML to embed a video without the <embed> tag, which is what breaks validation.

Nice! That was easy! I’ve tested this in all browsers on XP, Vista, Windows 7, and OSX – no problems!

Sizing video elements with just CSS

This one is a little bit trickier. First off we’re going to need a box that wraps the video element that maintains an aspect ratio; that is, one where the height adjusts to the width.

To do this, we’ll use a handy trick – using padding. Padding is cool. If you set the width of an element to 100%, then the padding top / bottom can be expressed as a percentage of this width. So for instance, if you had a column that is 400px wide, and you give an element inside it a width of 100% and a padding-top of 25%, it would get padding-top of 100px.

Here’s an example of this in action. Resize the browser window, and you can see the height will always stay 25% of the width.

So now we have a way to create a placeholder for our video. We’ll position our video inside using absolute positioning. A couple more things:

  • An extra sleeve element is required for our dear friend IE
  • The padding bottom to use is 56.25% for the ratio (it’s a 16:9 video, so it’s 9 / 6 = 0.5625), for 3:4 ratio videos you’d use 75%
  • The padding top is for the player’s controls (25px in this case)
  • You have to set the percentage on the padding-bottom, again, for IE

Here’s the finished code. You can open it up in jsFiddle and resize the browser window to see it automatically resizing to the content.

So…what do you think? Do you know of any problems with this approach? Let me know in the comments!


About this entry