24 min read

In this article by Alex Libby, author of the book Responsive Media in HTML5, we will cover the following topics:

  • Adding responsive media to a CMS
  • Implementing responsive media in frameworks such as Twitter Bootstrap
  • Using the Less CSS preprocessor to create CSS media queries

Ready? Let’s make a start!

(For more resources related to this topic, see here.)

Introducing our three examples

Throughout this article, we’ve covered a number of simple, practical techniques to make media responsive within our sites—these are good, but nothing beats seeing these principles used in a real-world context, right?

Absolutely! To prove this, we’re going to look at three examples throughout this article, using technologies that you are likely to be familiar with: WordPress, Bootstrap, and Less CSS. Each demo will assume a certain level of prior knowledge, so it may be worth reading up a little first. In all three cases, we should see that with little effort, we can easily add responsive media to each one of these technologies. Let’s kick off with a look at working with WordPress.

Adding responsive media to a CMS

We will begin the first of our three examples with a look at using the ever popular WordPress system. Created back in 2003, WordPress has been used to host sites by small independent traders all the way up to Fortune 500 companies—this includes some of the biggest names in business such as eBay, UPS, and Ford. WordPress comes in two flavors; the one we’re interested in is the self-install version available at http://www.wordpress.org.

This example assumes you have a local installation of WordPress installed and working; if not, then head over to http://codex.wordpress.org/Installing_WordPress and follow the tutorial to get started. We will also need a DOM inspector such as Firebug installed if you don’t already have it. It can be downloaded from http://www.getfirebug.com if you need to install it.

If you only have access to WordPress.com (the other flavor of WordPress), then some of the tips in this section may not work, due to limitations in that version of WordPress.

Okay, assuming we have WordPress set up and running, let’s make a start on making uploaded media responsive.

Adding responsive media manually

It’s at this point that you’re probably thinking we have to do something complex when working in WordPress, right? Wrong! As long as you use the Twenty Fourteen core theme, the work has already been done for you.

For this exercise, and the following sections, I will assume you have installed and/or activated WordPress’ Twenty Fourteen theme.

Don’t believe me? It’s easy to verify: try uploading an image to a post or page in WordPress. Resize the browser—you should see the image shrink or grow in size as the browser window changes size.

If we take a look at the code elsewhere using Firebug, we can also see the height: auto set against a number of the img tags; this is frequently done for responsive images to ensure they maintain the correct proportions.

The responsive style seems to work well in the Twenty Fourteen theme; if you are using an older theme, we can easily apply the same style rule to images stored in WordPress when using that theme.

Fixing a responsive issue

So far, so good. Now, we have the Twenty Fourteen theme in place, we’ve uploaded images of various sizes, and we try resizing the browser window … only to find that the images don’t seem to grow in size above a certain point. At least not well—what gives?

Well, it’s a classic trap: we’ve talked about using percentage values to dynamically resize images, only to find that we’ve shot ourselves in the foot (proverbially speaking, of course!). The reason? Let’s dive in and find out using the following steps:

  1. Browse to your WordPress installation and activate Firebug using F12.
  2. Switch to the HTML tab and select your preferred image.
  3. In Firebug, look for the <header class=”entry-header”> line, then look for the following line in the rendered styles on the right-hand side of the window:
    .site-content .entry-header, .site-content .entry-content,   .site-content .entry-summary, .site-content .entry-meta,   .page-content {
       margin: 0 auto; max-width: 474px;
    }
  4. The keen-eyed amongst you should hopefully spot the issue straightaway—we’re using percentages to make the sizes dynamic for each image, yet we’re constraining its parent container! To fix this, change the highlighted line as indicated:
    .site-content .entry-header, .site-content .entry-content,   .site-content .entry-summary, .site-content .entry-meta,   .page-content {
       margin: 0 auto; max-width: 100%;
    }
  5. To balance the content, we need to make the same change to the comments area. So go ahead and change max-width to 100% as follows:
    .comments-area { margin: 48px auto; max-width: 100%;   padding: 0 10px; }
  6. If we try resizing the browser window now, we should see the image size adjust automatically.

At this stage, the change is not permanent. To fix this, we would log in to WordPress’ admin area, go to Appearance | Editor and add the adjusted styles at the foot of the Stylesheet (style.css) file.

Let’s move on. Did anyone notice two rather critical issues with the approach used here? Hopefully, you must have spotted that if a large image is used and then resized to a smaller size, we’re still working with large files. The alteration we’re making has a big impact on the theme, even though it is only a small change. Even though it proves that we can make images truly responsive, it is the kind of change that we would not necessarily want to make without careful consideration and plenty of testing.

We can improve on this. However, making changes directly to the CSS style sheet is not ideal; they could be lost when upgrading to a newer version of the theme. We can improve on this by either using a custom CSS plugin to manage these changes or (better) using a plugin that tells WordPress to swap an existing image for a small one automatically if we resize the window to a smaller size.

Using plugins to add responsive images

A drawback though, of using a theme such as Twenty Fourteen, is the resizing of images. While we can grow or shrink an image when resizing the browser window, we are still technically altering the size of what could potentially be an unnecessarily large image!

This is considered bad practice (and also bad manners!)—browsing on a desktop with a fast Internet connection as it might not have too much of an impact; the same cannot be said for mobile devices, where we have less choice.

To overcome this, we need to take a different approach—get WordPress to automatically swap in smaller images when we reach a particular size or breakpoint. Instead of doing this manually using code, we can take advantage of one of the many plugins available that offer responsive capabilities in some format.

I feel a demo coming on. Now’s a good time to take a look at one such plugin in action:

  1. Let’s start by downloading our plugin. For this exercise, we’ll use the PictureFill.WP plugin by Kyle Ricks, which is available at https://wordpress.org/plugins/picturefillwp/. We’re going to use the version that uses Picturefill.js version 2. This is available to download from https://github.com/kylereicks/picturefill.js.wp/tree/master. Click on Download ZIP to get the latest version.
  2. Log in to the admin area of your WordPress installation and click on Settings and then Media. Make sure your image settings for Thumbnail, Medium, and Large sizes are set to values that work with useful breakpoints in your design.
  3. We then need to install the plugin. In the admin area, go to Plugins | Add New to install the plugin and activate it in the normal manner.

    At this point, we will have installed responsive capabilities in WordPress—everything is managed automatically by the plugin; there is no need to change any settings (except maybe the image sizes we talked about in step 2).

  4. Switch back to your WordPress frontend and try resizing the screen to a smaller size.
  5. Press F12 to activate Firebug and switch to the HTML tab.
  6. Press Ctrl + Shift + C (or Cmd + Shift + C for Mac users) to toggle the element inspector; move your mouse over your resized image.
  7. If we’ve set the right image sizes in WordPress’ admin area and the window is resized correctly, we can expect to see something like the following screenshot:

  8. To confirm we are indeed using a smaller image, right-click on the image and select View Image Info; it will display something akin to the following screenshot:

We should now have a fully functioning plugin within our WordPress installation. A good tip is to test this thoroughly, if only to ensure we’ve set the right sizes for our breakpoints in WordPress!

What happens if WordPress doesn’t refresh my thumbnail images properly?

This can happen. If you find this happening, get hold of and install the Regenerate Thumbnails plugin to resolve this issue; it’s available at https://wordpress.org/plugins/regenerate-thumbnails/.

Adding responsive videos using plugins

Now that we can add responsive images to WordPress, let’s turn our attention to videos. The process of adding them is a little more complex; we need to use code to achieve the best effect. Let’s examine our options.

If you are hosting your own videos, the simplest way is to add some additional CSS style rules. Although this removes any reliance on JavaScript or jQuery using this method, the result isn’t perfect and will need additional styles to handle the repositioning of the play button overlay.

Although we are working locally, we should remember the note from earlier in this article; changes to the CSS style sheet may be lost when upgrading. A custom CSS plugin should be used, if possible, to retain any changes.

To use a CSS-only solution, it only requires a couple of steps:

  1. Browse to your WordPress theme folder and open a copy of styles.css in your text editor of choice.
  2. Add the following lines at the end of the file and save it:
    video { width: 100%; height: 100%; max-width: 100%; }
    .wp-video { width: 100% !important; }
    .wp-video-shortcode {width: 100% !important; }
  3. Close the file. You now have the basics in place for responsive videos.

At this stage, you’re probably thinking, “great, my videos are now responsive. I can handle the repositioning of the play button overlay myself, no problem”; sounds about right?

Thought so and therein lies the main drawback of this method! Repositioning the overlay shouldn’t be too difficult. The real problem is in the high costs of hardware and bandwidth that is needed to host videos of any reasonable quality and that even if we were to spend time repositioning the overlay, the high costs would outweigh any benefit of using a CSS-only solution.

A far better option is to let a service such as YouTube do all the hard work for you and to simply embed your chosen video directly from YouTube into your pages. The main benefit of this is that YouTube’s servers do all the hard work for you. You can take advantage of an increased audience and YouTube will automatically optimize the video for the best resolution possible for the Internet connections being used by your visitors.

Although aimed at beginners, wpbeginner.com has a useful article located at http://www.wpbeginner.com/beginners-guide/why-you-should-never-upload-a-video-to-wordpress/, on the pros and cons of why self-hosting videos isn’t recommended and that using an external service is preferable.

Using plugins to embed videos

Embedding videos from an external service into WordPress is ironically far simpler than using the CSS method. There are dozens of plugins available to achieve this, but one of the simplest to use (and my personal favorite) is FluidVids, by Todd Motto, available at http://github.com/toddmotto/fluidvids/.

To get it working in WordPress, we need to follow these steps using a video from YouTube as the basis for our example:

  1. Browse to your WordPress’ theme folder and open a copy of functions.php in your usual text editor.
  2. At the bottom, add the following lines:
    add_action ( 'wp_enqueue_scripts', 'add_fluidvid' );
     
    function add_fluidvid() {
    wp_enqueue_script( 'fluidvids',     get_stylesheet_directory_uri() .     '/lib/js/fluidvids.js', array(), false, true );
    }
  3. Save the file, then log in to the admin area of your WordPress installation.
  4. Navigate to Posts | Add New to add a post and switch to the Text tab of your Post Editor, then add http://www.youtube.com/watch?v=Vpg9yizPP_g&hd=1 to the editor on the page.
  5. Click on Update to save your post, then click on View post to see the video in action.

There is no need to further configure WordPress—any video added from services such as YouTube or Vimeo will be automatically set as responsive by the FluidVids plugin. At this point, try resizing the browser window. If all is well, we should see the video shrink or grow in size, depending on how the browser window has been resized:

To prove that the code is working, we can take a peek at the compiled results within Firebug. We will see something akin to the following screenshot:

For those of us who are not feeling quite so brave (!), there is fortunately a WordPress plugin available that will achieve the same results, without configuration. It’s available at https://wordpress.org/plugins/fluidvids/ and can be downloaded and installed using the normal process for WordPress plugins.

Let’s change track and move onto our next demo. I feel a need to get stuck in some coding, so let’s take a look at how we can implement responsive images in frameworks such as Bootstrap.

Implementing responsive media in Bootstrap

A question—as developers, hands up if you have not heard of Bootstrap? Good—not too many hands going down

Why have I asked this question, I hear you say? Easy—it’s to illustrate that in popular frameworks (such as Bootstrap), it is easy to add basic responsive capabilities to media, such as images or video. The exact process may differ from framework to framework, but the result is likely to be very similar. To see what I mean, let’s take a look at using Bootstrap for our second demo, where we’ll see just how easy it is to add images and video to our Bootstrap-enabled site.

If you would like to explore using some of the free Bootstrap templates that are available, then http://www.startbootstrap.com/ is well worth a visit!

Using Bootstrap’s CSS classes

Making images and videos responsive in Bootstrap uses a slightly different approach to what we’ve examined so far; this is only because we don’t have to define each style property explicitly, but instead simply add the appropriate class to the media HTML for it to render responsively.

For the purposes of this demo, we’ll use an edited version of the Blog Page example, available at http://www.getbootstrap.com/getting-started/#examples; a copy of the edited version is available on the code download that accompanies this article. Before we begin, go ahead and download a copy of the Bootstrap Example folder that is in the code download. Inside, you’ll find the CSS, image and JavaScript files needed, along with our HTML markup file.

Now that we have our files, the following is a screenshot of what we’re going to achieve over the course of our demo:

Let’s make a start on our example using the following steps:

  1. Open up bootstrap.html and look for the following lines (around lines 34 to 35):
       <p class="blog-post-meta">January 1, 2014 by <a href="#">Mark</a></p>
         <p>This blog post shows a few different types of content that's supported and styled with Bootstrap.         Basic typography, images, and code are all         supported.</p>
  2. Immediately below, add the following code—this contains markup for our embedded video, using Bootstrap’s responsive CSS styling:
    <div class="bs-example">
    <div class="embed-responsive embed-responsive-16by9">
       <iframe allowfullscreen="" src="http://www.youtube.com/embed/zpOULjyy-n8?rel=0" class="embed-responsive-item"></iframe>
    </div>
    </div>
  3. With the video now styled, let’s go ahead and add in an image—this will go in the About section on the right. Look for these lines, on or around lines 74 and 75:
       <h4>About</h4>
         <p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit amet       fermentum. Aenean lacinia bibendum nulla sed       consectetur.</p>
  4. Immediately below, add in the following markup for our image:
    <a href="#" class="thumbnail">
    <img src="http://placehold.it/350x150" class="img-responsive">
    </a>
  5. Save the file and preview the results in a browser. If all is well, we can see our video and image appear, as shown at the start of our demo.

At this point, try resizing the browser—you should see the video and placeholder image shrink or grow as the window is resized. However, the great thing about Bootstrap is that the right styles have already been set for each class. All we need to do is apply the correct class to the appropriate media file—.embed-responsive embed-responsive-16by9 for videos or .img-responsive for images—for that image or video to behave responsively within our site.

In this example, we used Bootstrap’s .img-responsive class in the code; if we have a lot of images, we could consider using img { max-width: 100%; height: auto; } instead.

So far, we’ve worked with two popular examples of frameworks in the form of WordPress and Bootstrap. This is great, but it can mean getting stuck into a lot of CSS styling, particularly if we’re working with media queries, as we saw earlier in the article! Can we do anything about this? Absolutely! It’s time for a brief look at CSS preprocessing and how this can help with adding responsive media to our pages.

Using Less CSS to create responsive content

Working with frameworks often means getting stuck into a lot of CSS styling; this can become awkward to manage if we’re not careful! To help with this, and for our third scenario, we’re going back to basics to work on an alternative way of rendering CSS using the Less CSS preprocessing language.

Why? Well, as a superset (or extension) of CSS, Less allows us to write our styles more efficiently; it then compiles them into valid CSS. The aim of this example is to show that if you’re already using Less, then we can still apply the same principles that we’ve covered throughout this article, to make our content responsive.

It should be noted that this exercise does assume a certain level of prior experience using Less; if this is the first time, you may like to peruse my article, Learning Less, by Packt Publishing.

There will be a few steps involved in making the changes, so the following screenshot gives a heads-up on what it will look like, once we’ve finished:

You would be right. If we play our cards right, there should indeed be no change in appearance; working with Less is all about writing CSS more efficiently. Let’s see what is involved:

  1. We’ll start by extracting copies of the Less CSS example from the code download that accompanies this article—inside it, we’ll find our HTML markup, reset style sheet, images, and video needed for our demo. Save the folder locally to your PC.
  2. Next, add the following styles in a new file, saving it as responsive.less in the css subfolder—we’ll start with some of the styling for the base elements, such as the video and banner:
    #wrapper {width: 96%; max-width: 45rem; margin: auto;   padding: 2%}
    #main { width: 60%; margin-right: 5%; float: left }
    #video-wrapper video { max-width: 100%; }
    #banner { background-image: url('../img/abstract-banner- large.jpg'); height: 15.31rem; width: 45.5rem; max-width:   100%;
    float: left; margin-bottom: 15px; }
    #skipTo { display: none; li { background: #197a8a }; }
     
    p { font-family: "Droid Sans",sans-serif; }
    aside { width: 35%; float: right; }
    footer { border-top: 1px solid #ccc; clear: both; height:   30px; padding-top: 5px; }
  3. We need to add some basic formatting styles for images and links, so go ahead and add the following, immediately below the #skipTo rule:
    a { text-decoration: none; text-transform: uppercase }
    a, img { border: medium none; color: #000; font-weight: bold; outline: medium none; }
    
  4. Next up comes the navigation for our page. These styles control the main navigation and the Skip To… link that appears when viewed on smaller devices. Go ahead and add these style rules immediately below the rules for a and img:
    header {
    font-family: 'Droid Sans', sans-serif;
    h1 { height: 70px; float: left; display: block; fontweight:
    700; font-size: 2rem; }
    nav {
    float: right; margin-top: 40px; height: 22px; borderradius:
    4px;
    li { display: inline; margin-left: 15px; }
    ul { font-weight: 400; font-size: 1.1rem; }
    a {
    padding: 5px 5px 5px 5px;
    &:hover { background-color: #27a7bd; color: #fff; borderradius:
    4px; }
    }
    }
    }
  5. We need to add the media query that controls the display for smaller devices, so go ahead and add the following to a new file and save it as media.less in the css subfolder. We’ll start with setting the screen size for our media query:
    @smallscreen: ~"screen and (max-width: 30rem)";
     
    @media @smallscreen {
    p { font-family: "Droid Sans", sans-serif; }
     
       #main, aside { margin: 0 0 10px; width: 100%; }
       #banner { margin-top: 150px; height: 4.85rem; max-width: 100%; background-image: url('../img/abstract-     banner-medium.jpg'); width: 45.5rem; }
  6. Next up comes the media query rule that will handle the Skip To… link at the top of our resized window:
       #skipTo {
         display: block; height: 18px;
         a {
            display: block; text-align: center; color: #fff; font-size: 0.8rem;
           &:hover { background-color: #27a7bd; border-radius: 0; height: 20px }
         }
       }
  7. We can’t forget the main navigation, so go ahead and add the following line of code immediately below the block for #skipTo:
       header {
         h1 { margin-top: 20px }
         nav {
           float: left; clear: left; margin: 0 0 10px; width:100%;
           li { margin: 0; background: #efefef; display:block; margin-bottom: 3px; height: 40px; }
           a {
             display: block; padding: 10px; text-align:center; color: #000;
             &:hover {background-color: #27a7bd; border-radius: 0; padding: 10px; height: 20px; }
           }
        }
       }
    }

At this point, we should then compile the Less style sheet before previewing the results of our work. If we launch responsive.html in a browser, we’ll see our mocked up portfolio page appear as we saw at the beginning of the exercise. If we resize the screen to its minimum width, its responsive design kicks in to reorder and resize elements on screen, as we would expect to see.

Okay, so we now have a responsive page that uses Less CSS for styling; it still seems like a lot of code, right?

Working through the code in detail

Although this seems like a lot of code for a simple page, the principles we’ve used are in fact very simple and are the ones we already used earlier in the article. Not convinced? Well, let’s look at it in more detail—the focus of this article is on responsive images and video, so we’ll start with video.

Open the responsive.css style sheet and look for the #video-wrapper video class:

#video-wrapper video { max-width: 100%; }

Notice how it’s set to a max-width value of 100%? Granted, we don’t want to resize a large video to a really small size—we would use a media query to replace it with a smaller version. But, for most purposes, max-width should be sufficient.

Now, for the image, this is a little more complicated. Let’s start with the code from responsive.less:

#banner { background-image: url('../img/abstract-banner- large.jpg'); height: 15.31rem; width: 45.5rem; max-width: 100%;
float: left; margin-bottom: 15px; }

Here, we used the max-width value again. In both instances, we can style the element directly, unlike videos where we have to add a container in order to style it. The theme continues in the media query setup in media.less:

@smallscreen: ~"screen and (max-width: 30rem)";
@media @smallscreen {
...
#banner { margin-top: 150px; background-image: url('../img/abstract-banner-medium.jpg'); height: 4.85rem;     width: 45.5rem; max-width: 100%; }
...
}

In this instance, we’re styling the element to cover the width of the viewport.

A small point of note; you might ask why we are using the rem values instead of the percentage values when styling our image? This is a good question—the key to it is that when using pixel values, these do not scale well in responsive designs. However, the rem values do scale beautifully; we could use percentage values if we’re so inclined, although they are best suited to instances where we need to fill a container that only covers part of the screen (as we did with the video for this demo).

An interesting article extolling the virtues of why we should use rem units is available at http://techtime.getharvest.com/blog/in-defense-of-rem-units – it’s worth a read. Of particular note is a known bug with using rem values in Mobile Safari, which should be considered when developing for mobile platforms; with all of the iPhones available, its usage could be said to be higher than Firefox! For more details, head over to http://wtfhtmlcss.com/#rems-mobile-safari.

Transferring to production use

Throughout this exercise, we used Less to compile our styles on the fly each time. This is okay for development purposes, but is not recommended for production use. Once we’ve worked out the requisite styles needed for our site, we should always look to precompile them into valid CSS before uploading the results into our site.

There are a number of options available for this purpose; two of my personal favorites are Crunch! available at http://www.crunchapp.net and the Less2CSS plugin for Sublime Text available at https://github.com/timdouglas/sublime-less2css.

You can learn more about precompiling Less code from my new article, Learning Less.js, by Packt Publishing.

Summary

Wow! We’ve certainly covered a lot; it shows that adding basic responsive capabilities to media need not be difficult. Let’s take a moment to recap on what you learned.

We kicked off this article with an introduction to three real-word scenarios that we would then cover. Our first scenario looked at using WordPress. We covered how although we can add simple CSS styling to make images and videos responsive, the preferred method is to use one of the several plugins available to achieve the same result.

Our next scenario visited the all too familiar framework known as Twitter Bootstrap. In comparison, we saw that this is a much easier framework to work with, in that styles have been predefined and that all we needed to do was add the right class to the right selector.

Our third and final scenario went completely the opposite way, with a look at using the Less CSS preprocessor to handle the styles that we would otherwise have manually created. We saw how easy it was to rework the styles we originally created earlier in the article to produce a more concise and efficient version that compiled into valid CSS with no apparent change in design.

Well, we’ve now reached the end of the book; all good things must come to an end at some point! Nonetheless, I hope you’ve enjoyed reading the book as much as I have writing it. Hopefully, I’ve shown that adding responsive media to your sites need not be as complicated as it might first look and that it gives you a good grounding to develop something more complex using responsive media.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here