Embedding videos with automatic responsive layout

By using a couple of code lines in CSS and jQuery we can easily adapt the dimensions of an embedded iFrame – such as a YouTube or Vimeo video – to our responsive layout.

First, we need to create a  wrapping div. In order to avoid inserting it manually every time we embed a video, we can just use a simple jQuery command, included in our custom script .js file or directly in the page within a script tag.

We also overwrite the default width and height values with 100%.

$(document).ready(function() {
    $('#post iframe').attr('width','100%').attr('height','100%').wrap('<div class="embed-container"></div>'); } });

Then we need to define the CSS style for this container. Assuming a 16:9 ratio, we can use the code posted by Ander Andersen on amobil.se:

.embed-container {position: relative;
padding-bottom: 56.25%; /* 16/9 ratio */
padding-top: 30px; /* IE6 workaround*/
height: 0;
overflow: hidden;

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

This should do the trick. A nice thing is that from now on we can also just copy and paste the YouTube video page URL in WordPress and the responsive iframe will be conveniently created on the fly!

Leave a comment