How to make YouTube videos responsive in WordPress

In this short tutorial we’ll see how to make all YouTube videos responsive in WordPress.

The Problem

WordPress has a nice feature of automatically embedding YouTube videos with just posting the link of them (something like https://www.youtube.com/watch?v=XXXXXXXXXXX) in the editor. This feature is really cool, since you don’t need to collect the embed-link yourself from the video. But the problem is that these embedded videos are not responsive in the front-end as of yet, if the theme you are making doesn’t have added support for that. Today, we’ll solve this problem by adding a few lines of jQuery in the theme to add this functionality.

The Solution

We’ll use the following jQuery code to make the videos responsive. Just make sure that you call the the_content() function to return the content of the post inside an element .post-content in your template.

This code will find all YouTube iframes inside .post-content and make them take the full width of it on window load or resize event. Of course, the video height will also change with its width accordingly following the 16:9 aspect ratio.

This code would be enough for most cases. However, if your .post-content element is too wide (full screen, as an example), it may cause a scenario for a 16:9 screen where a part of the video will be vertically cut off since the browser’s title bar and address bar take up some space of the screen. In that case, you can use the following code to restrict the width of the video to a certain pixel. The logic used here is very simple:

  1. If the width of the video is less than the width of .post-content, then the video will expand to a certain maximum size.
  2. If the width of the video is more than the width of .post-content, then the video will fit inside to avoid any overflow.

To go a step further, if you are restricting your video’s width to a maximum and also want to center-align it, then you can use the following CSS:

.post-content iframe[src*="https://www.youtube.com"] {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

Hope this helps you. Good luck!

Advertisements

Ask a question or leave a reply!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s