Andrew in Week 9

Week 9 - Media Queries for Responsive Layouts

Introduction to Responsive Web Design

Some of this introduction will actually depend on some of the stuff we'll talk about a bit later. This is not an assignment. Rather, this is meant as a demonstration, and I will walk through the material as we go. You will see the concepts in action, and later on we'll discuss them in more detail (and you'll have a chance to implement them).

Downloads for Introduction to Responsive Web Design


Basic Responsive Design

The same holds true for this section. You'll see some of the basics implemented, with me putting them into action. I'll walk through the code additions, and you'll see - step-by-step - what impact each has. Later, we'll discuss these things in greater detail (and you'll have a chance to implement them).

Downloads for Basic Responsive Design


Jumping Spider Diaries Site - Responsive Design

Download

Non-Responsive Site: Jumping Spider Diaries

Download and unzip the site folder above. (You can view the site in a browser here: Non-Responsive Jumping Spider Diaries Site.)

Rename the site folder responsive, because that's what your about to make it be! When you're done with the eight (8) related RESPONSIVE EXERCISES below, zip up the responsive directory and submit it via the appropriate dropbox. The exercises are as follows:

  • 1: font-size in em
  • 2: widths in percentages
  • 3: proportional padding and margins
  • 4: scalable images
  • 5: first breakpoint
  • 6: first media query
  • 7: viewport meta tag
  • 8: complete your responsive design

Elements of Responsive Design

Ems Versus Pixels

Instead of using px for font sizes, use the unit of measure called em. An em is a unit equal to your default font size, which is 16px in most browsers (so 1em = 16px in most browsers). Everything is then measured in terms of em. This makes your website more scalable for all devices.

TARGET / CONTEXT = RESULT

To calculate em instead of px, use the handy formula above.

Example: if you want the #wrapper's font to be 14px, the formula is:

14/16 = 0.875em

That's "target of 14px divided by the default font size of 16px equals 0.875em".

SPECIAL CARE MUST BE TAKEN WITH COMPOUND SELECTORS

Once you define a main em size for fonts in a given container, font sizes within that container now have a new context.

Example: If I now want an h1 inside the #wrapper to be 36px, I need to use this formula:

36/14 = 2.571428571428571em

That's "target of 36px divided by #wrapper font size of 14px equals 2.571428571428571em". Yes, you really will see em sizes with many decimal places in responsive designs!

RESPONSIVE EXERCISE 1: font-size in em

Change the title for the Jumping Spiders Diary site to "Responsive Layout" (without the quotes). In the stylesheet, swap all the font sizes from px to em. Round to five decimal places. Leave yourself some CSS comments after each change to remind you what the original pixel sizes were.

By way of example:

font-size: 4.42857em; /* 62px */

Test in a browser to confirm all your font sizes are the same as before.

Fluid Grids

Fluid grids respond to the open width of the browser window. The wider or narrower the window, the wider or narrower the content and columns within it.

PAGE CONTENT WIDTHS DEFINED AS PERCENTAGES

For a grid to be fluid, widths of all box elements must be defined as percentages instead of px. This includes:

  • width
  • margins
  • paddings
  • borders

Within a given container, the total widths of all its children ought to add up to 100%. This makes the page content areas resize proportionally as the browser resizes. Currently, the Jumping Spider Diaries site uses fixed widths.

MEDIA QUERIES

Along with fluid grids, designers can use media queries to detect the current width of the browser window, known as the viewport, and adapt the layout accordingly.

Example:Try resizing the window with Smashing Magazine in it. Notice how the multiple sidebars find new places to live according to heirarchy? Here's what the site looks like on a wide-screen monitor:

smashingmag

The rearranging of page content blocks is being accomplished partly through the use of media queries. More on these later.

Percentages Versus Pixels

The formula you use to calculate percentages is similar to the one for figuring out ems: Target / Context = Result, except now you need to multiply the result by 100.

Example: If my wrapper is 960px and I want to convert my 300px sidebar into a percentage:

300/960 * 100 = 31.25%

That's "target of 300px divided by #wrapper width of 960px equals 0.3125, multiplied by 100 to get 31.25%".

RESPONSIVE EXERCISE 2: Widths in percentages

In the stylesheet for the Jumping Spiders Diary site, swap all widths from px to percentages for the following boxes. Round to five (5) decimal places.

  • nav (orig. 180px)
  • article (orig. 600px)
  • aside (orig. 180px)

For the wrapper, set it to 100% width but limit its width to no greater than 960px and no less than 350px, like this:

#wrapper {
	width: 100%;
	max-width: 960px;
	min-width: 350px;
}
			

Again, leave yourself comments as to the original sizes in pixels when they are converted to percentages. Now, check the page in a browser while you resize the window. How can we make things work better?

Proportional Paddings and Margins

Paddings and margins should all be defined as percentages too, when they occur on the left and right within a container.

Example: If my sidebar was originally set to 300px and I have an h1 inside it with a pargin of 15px, I need to calculate what percentage of 300 15 represents.

15/300 * 100 = 5%

RESPONSIVE EXERCISE 3: Proportional padding and margins

In the stylesheet for the Jumping Spiders Diary site, replace margin-left, margin-right, padding-left, and padding-right values with percentages. Round to five (5) decimal places. If a margin or padding is already set to 0, leave it alone, since zero works for any unit of measurement.

You might need to rethink the way selectors are combined to address the various contexts. In particular, you'll need to split out this one: h1, h2, h3, h4, h5, h6, p.

Leave copious CSS comments again. As you work, test in a scaling browser window. After you're done, what else needs to be fixed?

Scalable Images

Images can be set to a specific width in the markup, but then given a maximum width given their context, using max-width: 100%;

This ensures that images will resize when their containers get smaller than they are.

Example: I want any images placed in the markup to get smaller when they no longer have room to fit inside their respective containers.

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

Note: The height: auto declaration will override any height attributes set in your img tags.

RESPONSIVE EXERCISE 4: Scalable images

In the markup for the Jumping Spiders Diary site, remove all height attributes from the img tags. In the stylesheet, set the max-width for all images to 100%. Test in a browser. Now we're getting somewhere, but it would be nice to have the page sections stack on top of each other at some point when the browser gets to narrow, instead of squishing themselves three-across.


Implementing Adaptive Design

The adaptive design approach means using the same markup but adapting the CSS to various viewports, using media queries. You can do adaptive layouts without using a fluid grid. Ours is already fluid, but the following techniques can be used with a fixed-width site.

The first thing you need to do is determine the browser widths at which your layout will need to change.

Finding Your Breakpoints

Resize the Jumping Spider Diaries site, starting from full size, and going down until you feel like some or all of the content is getting too tight horizontally. Determine how wide the browser is at this point - that's your first breakpoint.

One way to measure the width of your browser window is with Tools > Web Developer > Responsive Design View (Ctrl + Shift + M) in Firefox (if it is enabled!). There is another tool in Chrome Canary, but the Firefox tool is specially designed to make your responsive design life easier.

Make a note of how wide the screen must be at a minim to maintain its current page content arrangement. Then determine what needs to go where when the page gets narrower than that width.

RESPONSIVE EXERCISE 5: First breakpoint

Find your first breakpoint in the spider site. Decide what needs to move out of the way, and where to, when the browser gets smaller than the breakpoint. What else should adapt/resize?

Creating Media Queries

A media query is something you wrap around a set of CSS rules that tests for certain things going on in the browser, and applies those rules if the query is positive.

You should always put media queries at the bottom of your stylesheet, or even in another stylesheet, so that they override all previously-defined styles when a given criterion is met.

Here's an example:

@media screen and (max-width: 460px) {
	header h1 {
    	font-size: 1.5em; /* 24px */
    }
}
			

This media query checks whether the rendering device is a screen (as opposed to a printer or other non-display device) and checks whether the browser window has reduced to 460px wide or less. If both of these are true, the h1 in the header is given a new font-size.

There are many other things you can check for in the browser environment, but we will focus today on screen and max-width.

Be sure to notice the extra set of { } brackets.

RESPONSIVE EXERCISE 6: First media query

Write a media query at the bottom of your stylesheet which tests for screen and your breakpoint width defined in exercise 5 above.

Write some rules inside your media query that change the layout and resize things to provide a better user experience at this size.

For example, you might remove float:left from a page block, with an according adaption of the widths for it and its neighboring block(s).

If you want to set the menu horizontally, you can add a float:left to it, but make sure there's room to do it - it can't be a sidebar anymore!

Viewport Meta Tag

Some devices may ignore your responsiveness and instead try to show your website full-width and zoomed out. This is okay for non-responsive sites, but you don't want that browser behavior to happen on your site.

So, we add a bit of markup into the head of our HTML page:

<meta name="viewport" content="initial-scale=1.0, width=device-width" />
            

This tells the browser that the width of the browser window should be treated the same as the overall device width.

RESPONSIVE EXERCISE 7: Viewport meta tag

Add the viewport meta tag to your index page.


Implementing Responsive Design

Responsive websites are built on a fluid grid and use media queries not to target specific device resolutions, but rather to adjust the design and content as it reaches various breakpoints.

So, you have everything you need to create a basic responsive site! There are a lot more techniques out there, and more are being suggested all the time, but this is all you really need to get started:

  • define font-size in em
  • define page block widths in percentages
  • make margins and paddings on the left and right proportional with percentages
  • make images scale
  • identify breakpoints
  • write media queries for breakpoints

RESPONSIVE EXERCISE 8: Complete your responsive design

Define at least three more breakpoints for the Jumping Spiders Diaries site, and give each breakpoint a media query with some new CSS rules.

Here are screenshots of how the site should be configured at reducing widths. Try your best to match these. (Note the fact that these resolutions sorta give away the neighborhoods of your breakpoints.)

1024px

jumpingspider1024

~974px

jumpingspider974

~910px

jumpingspider910

~640px

jumpingspider640

~460px

jumpingspider460

Mobile First

The trend toward mobile is picking up a lot of speed. (For example, I probably access websites on my phone and tablet just as often as I do on my home pc. Many people spend more time perusing websites on their mobile devices than they do on pcs or laptops.) There will come a time very soon that the majority of traffic on websites is coming from mobile devices. It is for this reason that many web designers are now thinking "mobile first."

This mobile first philosophy involves designing your layout for the smallest mobile design initially, and then working in the opposite direction from our approach in today's discussion. Smaller-to-bigger, rather than bigger-to-smaller.

In the mobile first method, you would write all your CSS for the basic site according to what works at about 350px across. Then your breakpoints work from in to out. When working this way, your media queries at the bottom of your stylesheet start with the next narrowest breakpoint (say, 450px) and go larger as you go down the page.

This also means you wouldn't use max-width, but instead would use min-width.

Example:

@media screen and (min-width:768px) {
	.main {
    	width:74.24243%;
        float:left;
    }
    .complementary {
    	width:22.72727%;
        float:right;
    }
}
            

More Responsive Concepts

Want to know much more about responsive design? Here's the first in a series of articles that go into much greater depth about the things we've covered this week:


Video Tutorials

Here's a great set of video/interactive tutorials on implementing responsive web design:

Note: This requires a paid membership to view in its entirety. Therefore, it is most certainly not a requirement for this class.


Responsive Site Exercise: Minced Kitten Web Design

Download

Instructions

Code this site to be responsive. When you are done, zip up your directory and submit it via the appropriate dropbox.

Helpful Hint

Use CSS to add in little bits of images after an element, such as the ribbon edges in the design above. For example, you might write a rule similar to this:

#calltoaction:after {
	content: url(images/ribbon-bottom.gif);
}
            

More here: "Learning To Use The :before and :after Pseudo-Elements In CSS"