Making video responsive

Flexible videos are somewhat more complex than images. The HTML5 <video> maintains its aspect ratio just like images and therefore we can apply the same CSS principle to make it responsive:

   video {
      max-width: 100%;
      height: auto !important;
   }

Until relatively recently, there have been issues with HTML5 video—this is mainly due to split support for the codecs required to run HTML video. The CSS required to make a HTML5 video is very straightforward, but using it directly presents a few challenges:

  • Hosting video is bandwidth intensive and expensive
  • Streaming requires complex hardware support in addition to video
  • It is not easy to maintain a consistent look and feel across different formats and platforms

For many, a better alternative is to host the video through a third-party service such as YouTube. There is a caveat that they would be in control of your video content; if this isn't an issue, we can let them worry about bandwidth issues and providing a consistent look and feel; we just have to make it fit on the page! This requires a little more CSS styling to make it work, so let's explore what is involved.

Embedding externally hosted videos

To embed those videos, we need to use iframes, which unfortunately do not maintain aspect ratio by default; we can work around this with a CSS solution by Thierry Koblentz.

Let's for argument's sake say that we have a YouTube video, such as this one, titled The Big Buck Bunny, by the Blender Foundation:

Embedding externally hosted videos

(c) Blender Foundation | www.bigbuckbunny.org

Looks okay, doesn't it? Granted, we can't immediately tell it is a video from YouTube, but this next screenshot clearly shows it is:

Embedding externally hosted videos

Hold on; that doesn't look right, does it? The screenshot was taken in Google, but set to emulate the screen estate of a Galaxy S5 mobile phone, but it clearly shows that the video is not responsive.

To see this in action, extract a copy of youtube.html from the code download that accompanies this book to our project area, then run it in a browser. Activate your browser's responsive mode (or device mode, depending on browser) and resize the screen to 360px by 640px. You will soon see how it doesn't resize well!

How do we fix this?

The trick is to create a box with a proper aspect ratio, say 4:3 or 16:9 (through zero height and bottom padding in %), and then fit the video and stretch it inside the box up to the box dimensions by positioning it absolutely with respect to the box. The bottom padding acts as the width that helps to maintain the aspect ratio. Let's alter our code to fix this issue:

  1. In youtube.html, add this link within the <head> section:
            <link rel="stylesheet" type="text/css" href="css/youtube.css"> 
    
  2. Further down, alter the code as shown:
            <div class="video-box-wrapper">
              <iframe width="560" height="315" 
              src="https://www.youtube.com/embed/XSGBVzeBUbk" frameborder="0" 
              allowfullscreen></iframe> 
            </div>
    
  3. Save the file. Switch to a new file, then add the following code and save it as youtube.css within the css subfolder of our project area:
            .video-box-wrapper { 
              padding-bottom: 5.25%; height: 0; position: relative;padding-top: 
              1.875rem; overflow: hidden; } 
     
            .video-box-wrapper iframe,  
            .video-box-wrapper object,  
            .video-box-wrapper embed { position: absolute; left: 0; top: 0; 
            width: 100%; height: 100%; } 
    

    Note

    A word of note—setting height: 0 ensures the element is present within the DOM so that older browsers can format the inner box properly.

  4. Save the file, revert back to your browser, and re-enable its responsive (or device) mode if it is not already switched on.
  5. Try previewing the results now; if all is well, we should see something akin to this. It uses the same Galaxy S5 size settings, but this time zoomed in to 150% for clarity:

    Embedding externally hosted videos

This looks much better! With some simple styling, we have the best of both worlds; we can let YouTube do all the heavy lifting while we concentrate on making our video available from our site on multiple devices. The CSS we used forces all of the video content to the full width of the .video-box-wrapper container, which in turn is positioned relative to its normal position. We then add 56.25% to the bottom to maintain the classic 16:9 aspect ratio and provide a little extra padding at the top so it doesn't appear to go off screen!

Note

Question: How did we arrive at 56.25%? This is simply 9 divided by 16 (the aspect ratio), which is 0.5625 or 56.25%.

There will be occasions, though, when we have to host our own videos; this might be for controlling visibility or preventing adverts from being played, if we were to host it externally. To achieve this, we can use the now current HTML5 <video> element to render content on a page; let's take a look and see how this works in action.

Introducing the new HTML5 video element

If hosting videos on an external source is not possible, then we must host locally; for this, we can use the native HTML5 video tag, which looks something like this:

<video controls> 
  <source src="video/bigbuckbunny.webm" type="video/webm"> 
  <source src="video/bigbuckbunny.mp4" type="video/mp4">  
</video> 

In the past, codec support for the HTML5 element has been split across each platform; in 2015, Firefox added support for H.264 to its browsers across all platforms, which goes a long way to rationalize support for HTML5 video. At present, support for the two formats (MP4 and WebM) is good, but not 100% across all browsers – this screenshot indicates the current state of play for desktop and mobile browsers for the MP4 format:

Introducing the new HTML5 video element

Source: CanIuse.com

In contrast, support for the WebM format is not quite so complete:

Introducing the new HTML5 video element

Source: CanIuse.com

In reality, the only format we need to worry about using is MP4; we can use WebM format if desired. If we do so, then it must come first in the <source> list; otherwise, the browser will pick the first available supported format (in this case, MP4) and not use WebM!

Tip

Before continuing, I would strongly recommend making sure you have Google Chrome or Firefox installed - WebM video will work in IE9 or above, but not without adding codec support for the format!

Now that we've been introduced, let's move on and put it into practice, with a simple demo to illustrate how the <video> element works in action.

Embedding HTML5 video content

If our requirements are such that we have to host a video ourselves, then implementing it using the HTML5 standard tags is very easy; it consists of setting any number of different sources within the <video> tags so that we can play the same video using the supported format for that browser. Let's dive in and take a look at how we do it:

  1. We'll start by extracting copies of the following, from the code download that accompanies this book - the video folder and html5video.html. Save them to the root of our project folder.
  2. In a new file, go ahead and add these styles; save the file as html5video.css in the css subfolder of our project area:
            video { 
               max-width: 100%; 
               /* just in case, to force correct aspect ratio */ 
               height: auto !important; 
            } 
    
  3. Try previewing the results in a browser. If all is well, we should see something akin to this (screenshot taken from Chrome):

Embedding HTML5 video content

The result looks perfect—the question is, which version of our video is being used? One way to find out is to right-click on the video, while it is still playing, then click on Save video as.... If all is well, we should see a Save As dialog box open, ready to save the WebM format if we're using FireFox, Chrome, or Opera; otherwise it will be MP4 (if using IE).

Exploring what happened

The real question, though, is not so much how does it all work, but if it is responsive?

The answer is yes; our use of the HTML5<video> tags mean that we can select any number of different video formats to use; the browser will simply choose the first available that it is able to play. The order is critical though:

<video controls> 
    <source src="video/bigbuckbunny.webm" type="video/webm"> 
    <source src="video/bigbuckbunny.mp4" type="video/mp4"> 
</video> 

If we were to swap it around so that MP4 is first, then WebM will be ignored for almost all browsers, as MP4 can be played in almost all of the browsers!

The real magic lies not in the use of a specific video format, but in the CSS rule we've created:

video { 
   max-width: 100%; 
   /* just in case, to force correct aspect ratio */ 
   height: auto !important; 
} 

Our use of percentage values means that it will automatically scale up or down when our window is resized; the maximum size of the video is constrained by the video's dimensions, not other elements on screen. Of course, we may decide to host the video within a parent container; the video will fill that container, but the parent may only stretch over part of the site.

Building a practical example

If you spend any time on the Internet, it's possible you've come across sites where the developer hasn't used images as a background, but video.

This isn't entirely new as a concept; it's been around for a couple of years now. If done with care, it can work very well. It's a perfect candidate for making full-size video as a responsive background. The great thing about it is that we can make it responsive using pure CSS. That's right, no need for any JavaScript.

For our next demo, we'll take a break from creating content. This time around, we'll run the demo from the code download that accompanies this book, and take a look at the code in more detail later in the demo. We'll be using videos from the Big Buck Bunny project, created by the Blender Foundation as our background; over this, we'll overlay a simple block of sample text, generated using the Lorem Ipsum generator.

To see this in action, go ahead and run the fullscreen .html demo from a copy of the code download that accompanies this book. If all is well, you will see the video play behind a simple <div> with text:

Building a practical example

If we take a look at our code in more detail, we can see the video element in use; it's been set to autoplay, with sound muted and a poster (or placeholder) image set. The real magic, though, lies in the CSS styling, so let's explore this in more detail.

Exploring what happened

The trick that makes our video work is in this code. We need to set two media queries with 16:9 aspect ratio (one as a min-aspect-ratio, another as the max) so that our video displays correctly on the screen:

Exploring what happened

When resizing it though, it will show white space. We fix that by setting negative margins, which makes the viewport much wider, and allows us to center the content on screen:

Exploring what happened

A key point to note is the values used for height, top, left, and width; although these seem extreme, they are required to help center the video on screen when viewing the content with a 16/9 aspect ratio set.

Perfect! Our video plays well. We can see the content without too much difficulty. Everything should be good, surely? Well, yes and no; concepts such as background video are not without their risks; it's important to understand where things might fall over if we're not careful. Let's pause for a moment and consider some of the potential traps that might upset the proverbial apple cart, if we're not careful with our video.

Exploring the risks

In our previous example, we explored the concept of adding video as background content. It's a fashion that has taken off within the last couple of years, and provides an interesting effect, that is different to seeing the standard images we might otherwise see!

It's not without a certain element of risk though; there are a few pointers we must consider, when adding video as the background content:

  • It's possible to add video, but we shouldn't just add it because we can—any video we add using this method must amplify the site's overall message.
  • Any video added will likely be set to autoplay, but the sound must be muted by default—if possible, it shouldn't have any sound at all.
  • Does our video fit with the site brand, tone, color palette, and so on? There is no point building a killer site, only to ruin it with a rubbish video.
  • Costs are something we must consider; it can be expensive to host video content, so it must be compressed as much as possible to keep file sizes down, and in a suitable format that works on multiple devices, including mobile.
  • Our video should not be too long; we must strike a balance between making it too long and not long enough so that it does not feel too repetitive.
  • Accessibility is a key pointer; it must be of sufficiently high contrast so as to make the text overlay legible.
  • Our video may look good, but what about performance? Your customers will not thank you if you produce a lightning fast site, but slow it down with a large, poorly optimized video as a background; they will very likely vote with their feet!
  • The compatibility technique we've used doesn't work on IE8, so a static placeholder must be included as a fallback; in the event the browser we use doesn't support HTML5 video or its attributes (such as autoplay, for mobiles).

Even though we have some clear pointers that should be considered, it should not stop us from using this effect; I'm one for pushing out the boundaries of what is possible, provided we do it well!

Making audio responsive

Question—we've worked on making videos responsive, but what about audio content?

Well, we can apply similar principles to the HTML5 <audio> element; instead of setting a specific width, we can use max-width and set a percentage figure to control how wide it displays on the screen.

The code to achieve this is very simple, and should by now be familiar—let's take a look at what is involved:

  1. For this demo, we need to avail ourselves of suitable files; for licensing reasons, you won't find any in the code download that accompanies this book, unfortunately! One way to achieve this is to take a copy of an iTunes file (normally in .m4a format), then use an online service such as Media.io (http://media.io/) to convert it to the right formats. You will need to convert to both MP3 and OGG formats, before continuing with this demo.
  2. Assuming we now have the right files, go ahead and extract a copy of audioelement.html from the code download that accompanies this book, and save it to the root of our project area.
  3. Next, at the root of our project area, go ahead and create a new folder called audio; into it, save copies of the audio files you either have or created from step 1.
  4. In a new file go ahead and add the following code, saving it as audioelement.css in the css subfolder at the root of our project area:
            audio { 
              max-width: 100%; 
              width: 800px; 
            } 
    
  5. Try previewing the results of our work in a browser—if all is well, we should see something akin to this screenshot:

Making audio responsive

At first glance, it may not look special, but then the <audio> element isn't meant to look anything out of the ordinary! The key here though is when we resize the browser window; we've set a max width value of 100%, but have constrained this by setting an upper limit of 50rem in the width attribute. No matter how many times we resize our window, the audio player will fill the full width, but not go any wider than 50rem.

Note

Unlike the <video> element, we can't resize the height using just CSS; to do this requires overriding the <audio> element with jQuery, which is out of the scope of this book.

Let's move on and put our new-found knowledge to the test to create a practical example—how about making a video fullscreen, and responding to changes in the browser viewport automatically? Setting up video using this technique is always fraught with controversy, but I'm not one to shy away from a challenge, so without further ado, let's dive in and see why we must step carefully when using video at fullscreen.

Taking things further

Throughout the course of this book, we've concentrated on using the core technologies of HTML5 and CSS3; in many cases, this is all we need, but there will come a time when we have to use other technologies to help fulfill a task, as we've outgrown the art of possible with plain CSS and HTML code.

Thankfully, there are lots of options available online to help with making videos responsive, and to take our skills. It goes without saying though that we should always ask ourselves if our need for another library is because the realities of life mean that we can't achieve our task without using it or if we've simply become too lazy!

If indeed we do need to download and use an additional library, there are a few good options to try out, which include:

  • FitVids.js: This plugin, available from http://fitvidsjs.com and built by Chris Coyier of CSS Tricks' fame, may be worth a look, although it hasn't been updated for at least 2-3 years.
  • MediaElement.js: It is available from http://mediaelementjs.com, and is a great library that works with both the <video> and <audio> elements; it allows us to override the standard element and customize it to our requirements using jQuery and CSS. There are plenty of examples of doing this online, along with suitable tutorials on how to achieve a custom look and feel to any player we skin using jQuery.

A small word of caution—a number of the video plugin libraries for jQuery haven't been updated for some time; you may well find that they no longer work properly with more recent versions of jQuery. This isn't necessarily a bad thing, as support for the HTML5 <video> and <audio> elements is now excellent; this renders many of these libraries surplus to requirements!

Note

Some of you may ask why we need to use jQuery to skin either HTML5 audio or video players; many of the individual elements are not accessible using plain CSS, and need JavaScript to expose those elements before styling them with CSS.

Phew! We're almost through this part of the journey, but before we move onto taking a look at using media queries in the next chapter, there is one more part of making responsive content; how about the text we have on our sites? It might not immediately strike you as being one we would associate with videos and text (at least in the context of making content responsive), but all will shortly become clear.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset