Book Image

Web Design Blueprints

Book Image

Web Design Blueprints

Overview of this book

The book delivers simple instructions on how to design and build modern Web using the latest trends in web development. You will learn how to design responsive websites, created with modern Flat User Interface design patterns, build deep-scrolling websites with parallax 3D effects, and roll-your-own single-page applications. Finally, you'll work through an awesome chapter that combines them all. Each chapter features actual lines of code that you can apply right away.
Table of Contents (12 chapters)
Web Design Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Working with responsive media


Media is a big deal in web design and development and is therefore a big deal in responsive web design and development. Our concern with preparing for media in our web development concerns optimization. We want to consider many factors, such as bandwidth use, but also, and perhaps more importantly, the size and pixel density of the device the media will be viewed on. This next section on responsive media will prepare you to handle these concerns.

Creating responsive images with srcset

Not too long ago, when developers wanted to make a truly responsive image, we had to construct server-side and client-side code to deliver a responsive image to the viewport. The client would detect and store the viewport size and send the data to the server when making requests for images. Much of the developers' discussion was centered on delivering the "right-sized" image to the device, and consideration of the user's bandwidth was a factor. This solution was burdensome enough that many developers opted to just send the large file anyway, instead of choosing among three (or more) versions of each picture, and let the CSS scale the image to fit in the viewport.

How things have changed

In recent history, the advent of high-density displays changed the focus of the discussion, and "right-sized" took on a new meaning. Now, high-density displays mean that you need to deliver a much larger file to the viewport—a game changer for sure. Now the larger file is more appropriate for mobile devices' high-density displays. This is a polar change from the original story, where the developer was considerate of the viewers' bandwidths.

The emerging technology of high-density displays is the driving force in this change in how we develop mobile apps. Now, responsive web design is liberated from the chains of developing for bandwidth limits, and we can now develop for more beautiful displays.

A brand-new solution

With that said, let's leave behind our cares about bandwidth for a moment and take a look at a new solution, srcset—a new attribute of the img element. It has only recently been implemented in select browsers. Not every browser has implemented this attribute, only the browsers that need it have it: the primary mobile browsers. If you want to know exactly which ones have it, take a look at Can I Use ____? (http://caniuse.com/#feat=srcset) for the most recent versions that have implemented this feature.

The srcset attribute allows the developer to define a list of sources for the image attribute, selected by the user agent based on the device's viewport pixel density ratio for each CSS pixel. Sounds convoluted, yes; it's sort of a pink unicorn hocus pocus, whatever that means.

Instead of me struggling to explain the hocus pocus, let's go through an example that demonstrates the property.

Enough theory, let's do something

Before we start with any code, let's get the content created. Get a hold of a large high-resolution image. If you don't have any, perform an advanced imaged search on Google; search for the subject, select Images, then Search Tools, and then set Size to Large. Then select an image you like, and save it to your hard drive.

Next, open it in your favorite image-editing software. If you don't have an image-editing software, or a favorite for that matter, you can download a free, open source image editing software from http://www.gimp.org/. GIMP has versions for Windows, Mac, and Linux. It's good enough for the purposes of resizing an image. In your new favorite photo-manipulating software, create the largest-sized image. I chose 1024 pixels and named it robot-large.png (because I think robots are really cool). Next, scale down the image to make two smaller images, one of 600 pixels, named robot-medium.png and the other of 300 pixels, named robot-low.png. Now that you have your images ready, place them into the img subdirectory of your project for later. From here, we can get on with the code.

Layout basics

You should already be familiar with the basics of layout, such as picking out your IDE and basic HTML tags. So launch your IDE and create an HTML page, as I have in the following code example. Remember your viewport; it's important:

<!DOCTYPE>
<html>
    <head>
    <title>Trying out SRCSET</title>
    <meta name="viewport" content="width=device-width" initial-scale=1 maximum-scale=1>
    </head>
    <body>
        //TODO add the content
    <body>
</html>

That was easy, wasn't it? I hope so. If not, go back to the beginning of the section and start over. Otherwise, your training has begun.

We are going to add the image soon, but first, let's get our CSS out of the way, as the bulk of the operation is a content issue, not a style issue. In your header, right before the closing header tag, add a style tag with CSS for the img element. Display it as block and with a width of 50%. You can add media queries later if you want to do some more involved work for the responsive design. These instructions are implemented in the following code:

<style>
img{
     display:block;
     width:50%;
}
</style>

That simple block of CSS is all we are going to do with CSS. Everything else will be handled within the img tag. The next sensible thing to do is add the img tag to our HTML. We will add an img tag with the src attribute set to robot-large.png. Don't forget your alt attribute for Section 508 compliance. See this demonstrated in the following code:

<img
    src='./img/robot-large.png'
    alt='a picture of a robot'
/>

The src attribute is the fallback called when the code is viewed on a browser that has not implemented srcset. This is an acceptable depreciation, as you will find this occurs only on some of the not-so-cool desktop browsers.

Making the img element responsive

Finally, let's get into the meat and potatoes of this subsection: the new attribute, srcset. We are going to list all three of the images we created, matched to the pixel density ratio we previously described. The attribute will take a comma-separated list of image name and pixel-density ratio pairs. For the very large pixel density screens, say those with three times as many pixels as a regular CSS pixel, we will use robot-large.png. Then, add the comma. For robot-medium.png, set it to be used with screens with twice the pixel density. Comma again. For the smallest version of your image, robot-low.png, attach it to the screens with comparable pixel density, such as normal monitors.

We use the x descriptor after the image name in srcset to determine the appropriate pixel density to match the image against. Look at this code sample:

<img
    srcset='./img/robot-high.png 3x,
    ./img/robot-medium.png 2x,
    ./img/robot-low.png 1x'
    src='./img/robot.png'
    alt='a picture of a robot'
/>

Viewing your responsive image

Next, launch the file in your browser. Open the Inspector (right-click, and select Inspect Element) and go to the Network tab. Refresh, and you will see that the browser has loaded robot-low.png, if you are working on a laptop with a normal pixel density.

Click on the mobile phone icon in the inspector window to start the mobile user agent emulator. Now, as you toggle between different types of device emulators, you will see that the appropriate image is loaded for devices with larger pixel densities. For example, the Samsung S4 loads the high-resolution file, while the iPhone 3 loads the medium-resolution image. If you do not see the change automatically, you may need to refresh the screen after you select a different device emulator. The following screenshots demonstrate the different renderings:

Beyond this cursory lesson, there are other features for images that are not yet implemented, so it's impractical to go beyond the x descriptor too much. There is another descriptor, the w descriptor, but it is not implemented in many browsers. In the future, this may be implemented, and then you can integrate with the sizes attribute.

The srcset attribute is a really big leap forward for interface development. It is difficult to conceptualize at first, but once you do, and match it to some clever media queries, such as ones we'll discuss soon, you can create some outstanding responsive UI work.

Creating responsive images with CSS

Images are a big deal in responsive design. Once we have the right image delivered to the viewport, we can use CSS to manage how the viewport renders the image. This is simple in theory. In practice, however, responsive design for images can be a little more complicated. It is important to have a good plan for how you want your design to handle images responsively.

In this section, we will go through some of the more complicated strategies; first, let's get started with the simple aspects of responsive design for images.

Getting started coding

The first part of this exercise is to create a simple webpage with an image in it. You can use the srcset example from the previous chapter if you already have it. If not, use the following example code. You should also place an image in a folder named img in your root directory:

<img
    srcset='./img/robot-high.png 3x,
            ./img/robot-medium.png 2x,
            ./img/robot-low.png 1x'
    src='./img/robot.png' alt='a picture of a robot'
/>

In your header, create a section for the CSS. You don't need a separate text file for your stylesheet; it won't be so complicated as to justify the extra complexity. Inside it, add a CSS style for the img element.

Responsive style

The img element is easy to make responsive. Simply give it a width of 100%, and set the height to auto so that the aspect ratio stays proportional. The 100% width will stretch the image to fill its wrapping element. Keep this in mind, as we will discuss it later. Look at the code in the following code sample:

<style>
    img{
        width: 100%;
        height: auto;
    }
</style>

Open your HTML document in your browser, and you will see the image stretched fully across your screen. Technically, this is responsive, but it does not respond in a good way. If the viewport area is wider than the image, then the image may become pixelated and blurry. This is certainly not optimal. So let's work on this some more.

Above and beyond

To prevent the image from exploding all over your viewport, you can add some more complexity to the CSS. Try limiting the width of the img element to the width of the actual image. To do so, you will need to change the width attribute to a max-width value of 100%. This small change allows the image to be responsive with the viewport changes limited to the maximum size of the image. This means that if the image is really only 300px, then that's as big as it will get. This starts to make sense if you can work out some good patterns along with the srcset attribute of the img element. You can see the additional CSS in the following code sample:

<style>
    img{
        max-width: 100%;
        height: auto;
    }
</style>

Often, you will not want your image to take up 100% of the viewport. Of course, there are a number of layouts where an image takes 100% of the viewport width. That aside, in your content area, your image may not be the most important piece of content in the viewport.

Responsive images can be difficult to manage, and you may want to have a more universal control over how the images look in a template. Additionally, you would probably never simply leave the image by itself on a page; you would likely have some wrapper around it for thoughtful layout control.

With that in mind, add a wrapping div element around your image and give it a class identifier. In this example, we can use foo:

<div class="foo">
<img
    srcset='./img/robot-high.png 3x,
            ./img/robot-medium.png 2x,
            ./img/robot-low.png 1x'
    src='./img/robot.png' alt='a picture of a robot' />
</div>

Now that the image is naturally resting inside of the layout element, you will change the CSS so that the image is maximized inside the wrapping div element, and the wrapping div element is used therefore for control of the layout. For this simple example, make the wrapping element to have a width of 30% of the viewport. Restyle the img to be a width of 100%.

<style>
    div.foo {
        width: 30%;
    }
    img{
        width: 100%;
        height: auto;
    }
</style>

Now we have better layout control of the image and how it is placed in the layout. Look at the example illustrated in the following screenshots:

Calculating the responsive image size

Speaking of layout, before we move on, let's briefly take a look at an example of how to determine the percentage width of an image for responsive design. Take a look at, or create a static layout (low-fidelity) version of, the page that is 1024px wide. Take an image and place it in the layout at 300px. To calculate the percentage of the image width, or the wrapping div, for our image, we simply need to divide the image width, 300 (px), by the layout width, 1024 (px). This gives us 0.2929, or roughly 29%. This is expressed as 300/1024 = 0.2929. And do not forget that if you are adding margins as padding, each must be doubled for both sides and added to the space it takes. Therefore, a 300px image with 2px horizontal padding and 2px horizontal margins will take up 308px of the horizontal width of the 1024px screen, which comes to 0.3001 or 30.01%. Keeping the vertical padding and margins as static pixels is recommended.

Adding responsive video to your site

This book would be incomplete without a section on how to create a responsive template for video. Video, as a medium, has become one of the most prolific forms of communication using the Internet. Hordes of people are seeking to become Internet-famous with their own YouTube channels, and these videos are posted all over blogs and shared with friends. Additionally, businesses want to include live-action shots of their products to demonstrate how they will help their customers. In fact, nearly every new site will likely have some video component.

Working with two use cases

This section will demonstrate how to create the template for embedding a video and controlling how it will display in your responsive site. There are different use cases to consider: first, you are hosting the video yourself, and second, you are embedding it hosted on another site using an iframe element. The second is more common as people often use a video-hosting service such as YouTube.

Use case #1 – self-hosted video

If you are hosting the video yourself, this is easy—just like a responsive image. Set up your video, and an example of the layout code is as follows:

<video width = "320" height = "240" controls = "controls">
    <source src = "movie.mp4" type = "video/mp4">
    <source src = "movie.ogg" type = "video/ogg">
    Your browser does not support the video tag.
</video>

Then, use CSS to give the video a percent width and an automatic height, as I have demonstrated here:

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

That was simple, but perhaps it is not the most pertinent of the use cases.

Use case #2 – embedded through the iframe element

Let's examine the use case of embedding the video through an iframe element. The typical method for embedding the video is as follows:

<iframe src = "http://player.vimeo.com/video/123456789" width = "800" height= "450" frameborder = "0">
</iframe>

The iframe element itself is not a responsive element, so we need to wrap it with an element that we can exert control over. Create a wrapping div with a video-wrap class, as I have in the following code:

<div class="video-wrap">
    <iframe src = "http://player.vimeo.com/video/52948373?badge=0" frameborder = "0">
    </iframe>
</div>

Responsive video CSS

This will allow us to use CSS to force the iframe element to behave responsively. For iframe itself, the CSS is simple: assign it an absolute position to the top at 0px and a 100% height and width. The wrapping div is where the magic happens. First, give it a relative position to the top at 0 also so that the iframe element is an absolute within a relative position. Then, assign it a 55% padding to the bottom and 30px to the top. Finally, hide the overflow. The code is shown here:

<style>
    .video-wrap {
    position:relative;
    padding-bottom: 55%;
    padding-top:30px
    height: 0;
    overflow:hidden;
    }
    .video-wrap iframe,
    .video-wrap object,
    .video-wrap embed {
    position:absolute;
    top:0;
    width:100%;
    height:100%;
    }
</style>

Modifying the layout

We have laid a good foundation for controlling the video iframe element. Next, we can make it responsive. Like a responsive image, we control the width of the video by making it consume 100% of its parent element width, and then we make the parent width responsive.

The next step will be to add another wrapping div element to the video. Give it a video-outer-wrap class, as I have in this sample code:

<div class="video-outer-wrap">
    <div class="video-wrap">
        <iframe src = "http://player.vimeo.com/video/52948373?badge=0" frameborder = "0">
         </iframe>
    </div>
</div>

Then add to the CSS attributes for video-outer-wrap, like the following code demonstrates:

.video-outer-wrap {
    width: 50%;
}

Viewing the example

Now, launch the file in your browser. This is a big improvement: we can control the size of the video in the viewport now. Look at the example in the following screenshots:

The next step to do on your own is to add some media queries so that, for different devices, you can have a different-sized video.

Communicating with responsive typography

In your responsive project, you must consider your typography. Typography is probably the most important part of responsive design, as the Internet's primary purpose is to convey information. Sure, there are plenty of pictures and video, but type is what makes the Internet useful. Therefore, a certain level of attention to type should be expected.

A question would arise: is there more to it than just setting the font just a few pixels bigger or smaller for the mobile viewport? Yes, of course. Think about the fact that the devices for which you will be designing can be quite diverse and will have different factors that affect your content's usability.

A good solution for responsive typography

A shiny happy new font size was introduced in CSS3, rem. It is similar to em, which means relative to the font size of the element. rem means relative to the size of the root element. This means that you set the font size at the root or HTML identifier in your CSS and then, for an element, set the size relative to the root with rem.

Working with an example

To try a bold experiment, create a new HTML document and add three paragraphs of text. Give them each a different class identifier. See how I have done it in the following code:

<p class="foo">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eget finibus dolor. Cum sociis natoque penatibus et magnis dis parturient montes
</p>
<p class="bar">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eget finibus dolor. Cum sociis natoque penatibus et magnis dis parturient montes
</p>
<p class="gup">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eget finibus dolor. Cum sociis natoque penatibus et magnis dis parturient montes
</p>

Create the typography's CSS

Next, create the CSS for the root HTML element and the three p elements. The root needs to have the font size defined. Give it a font-size value of 60% of its default size. Then, for each paragraph, assign a font-size attribute of 1rem, 2rem, and 3rem. This is demonstrated in the following code:

<style>
    html{font-size:60%;}
    p.foo{font-size:1rem;}
    p.bar{font-size:2rem;}
    p.gup{font-size:3rem;}
</style>

Different rem font sizes will appear differently in the viewport. Now that we've illustrated a point, let's change the demonstration to be a responsive demonstration of rem font sizes. Next, we will add media queries to our CSS to demonstrate responsive typography. Add new media queries for breakpoints at 320px, 768px, and 1024px. Look at the following code sample:

<style>
    @media screen and (max-width:320px)
    {
    }
    @media screen and (min-width:320px) and (max-width:768px)
    {
    }
    @media screen (min-width:768px) and (max-width:1024px)
    {
    }
    @media screen (min-width:1024px)
    {
    }
</style>

Next, add the font size by rem CSS to each of the series of media queries, like this:

<style>
    @media screen and (max-width:320px)
    {
        html{font-size:60%;}
        p.foo{font-size:3rem;}
        p.bar{font-size:3rem;}
        p.gup{font-size:3rem;}
    }
    @media screen and (min-width:320px) and (max-width:768px)
    {
        html{font-size:60%;}
        p.foo{font-size:2rem;}
        p.bar{font-size:2rem;}
        p.gup{font-size:2rem;}
    }
    @media screen and (min-width:768px) and (max-width:1024px)
    {
        html{font-size:100%;}
        p.foo{font-size:1rem;}
        p.bar{font-size:1rem;}
        p.gup{font-size:1rem;}
    }
    @media screen and (min-width:1024px)
    {
        html{font-size:60%;}
        p.foo{font-size:1rem;}
        p.bar{font-size:1rem;}
        p.gup{font-size:1rem;}
    }
</style>

Finished!

Now, save you progress and refresh your screen. Launch your mobile device emulator and you will be able to run a battery of tests to see how this typography is effected on different devices. Look at these sample screenshots: