Embedding a YouTube Player with Responsive Aspect Ratio

msgarcia
Community Contributor
8
9407

The Challenge

Canvas does a pretty good job of handling responsive design via the Rich Content Editor, but, if there is one thing that I have found I am not the biggest fan of, it is the video thumbnails. Dropping a video into a course and having it simply represented by a small thumbnail just bothers me. I know that I can just link to a YouTube video as an External Tool in a module as well, but I want to include buttons, links, and text in the pages to accompany my videos.

Additionally, simply copying the embed code of a YouTube video gives you set dimensions for the iframe that you drop into your page. The end result is a video container that is either too narrow or too wide depending on the device that you choose to use. Furthermore, while I could have easily set the width of the video container to 100%, making it fluidly adjust to the width of the page, the iframe's height would remain he same, which would give me black, spacing bars on either side of the video.

What I really wanted was to be able to embed my YouTube videos on a page so that I could also enable custom thumbnails for the videos and maintain their aspect ratio no matter the device that was used to view them.

Solution

While javascript is an obvious choice for resizing elements, the solution for this issue was actually much easier than I realized. I found the following gist by GitHub user jaicab which detailed a pure CSS method for handling this. Recognizing that I didn't have access to the global CSS for my organization's instance of Canvas, I instead chose to utilize his CSS inline with the paragraph element in Canvas, and the iframe element that is generated for the purposes of embedding YouTube videos. The resulting code for the video looks like this:

<p style="border: 1px solid #d7d7d7; position: relative; padding-bottom: 56.25%; padding-top: 30px; height: 0; overflow: hidden;">
<iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none" src="https://www.youtube.com/embed/xcdzCwuFmCs?showinfo=0" width="420" height="315" allowfullscreen="allowfullscreen"></iframe>
</p>‍‍‍‍‍‍

You can view and resize the container itself on my jsfiddle account here. Another reason that I like to use the embeddable iframe element is that it also allows me to utilize additional video parameters that YouTube has available including video start/end times, modest branding, and autoplay.

If you would like to test it out using any other YouTube video, simply replace my iframe src parameter with the src parameter from the embed code of your video of choice!

8 Comments