Lesson 18

Using Media Queries and Breakpoints

What You’ll Learn in This Lesson:

  • Image How to write a CSS media query

  • Image How to use different media types

  • Image How to create media query expressions

  • Image Understanding logical keywords in your queries

  • Image What CSS breakpoints are

  • Image How to define breakpoints

  • Image How to find the best breakpoints for your website

For many people, the term responsive web design is synonymous with CSS media queries. And while it’s possible to have a responsive site without using media queries, using them is the most common way of doing RWD. This lesson will take you through how to write a media query as well as what the different types of queries, keywords, and expressions are.

Breakpoints are the points where media queries adjust the design. Even if you have only one breakpoint, your web page will respond to the presence of that breakpoint and respond appropriately to user agents that match. In this lesson you will learn what breakpoints are and how to use them. Plus, you’ll learn what makes good breakpoints to support a wide variety of devices.

What Is a Media Query?

According to the W3C, a media query is a “logical expression that is either true or false. A media query is true if the media type of the media query matches the media type of the device.…” What this is saying is that a web designer can use a media query to define if/then statements based on the characteristics of the device viewing the page.

CSS media types were introduced in the CSS specification in CSS2, and media queries were added in CSS3. Media queries became a full-fledged recommendation in June 2012, but they have been supported by browsers since before 2010. CSS media queries are a stable tool, and web designers should feel confident that modern browsers and user agents support them.

When you are building a media query, you use the @media rule. You then define the media types the rule applies to, as well as the features of that type that you want to focus on. You place these rules right in your CSS style sheet, using the following syntax:

@media mediaType and (mediaFeature) {  }

Using Media Types

There are 10 media types you can test for with CSS media queries:

  • Image all—All media

  • Image braille—Braille and tactile feedback devices

  • Image embossed—Paged braille printers

  • Image handheld—Small-screen low-bandwidth handheld devices

  • Image print—Paged media and documents in print preview mode

  • Image projection—Projected presentations

  • Image screen—Color computer screens

  • Image speech—Speech synthesizers

  • Image tty—Teletypes and media with a fixed-pitch character grid

  • Image tv—Television

Caution

The handheld media type was originally used to apply to cell phones and PDAs and other handheld devices, but most cell phone manufacturers wrote their devices to report back a screen media type because they didn’t want their customers to be penalized by web designers not wanting to give handheld customers the full experience. So you cannot rely on this media type to detect mobile devices.

The most common media type web designers use is screen because modern cell phones, tablets, and all computer monitors use this designation.

You can use the print media type to create a style sheet for printing web pages. This common way of using media types allows web designers to control how their web pages look when they are printed out.

To create a print style sheet, open a new CSS document for your print styles. Best practices recommend that you do things like remove advertising, change the color of links to the text color, add underlines to links if they are removed, and remove the background colors so they don’t print.

You load a style sheet as you would a normal style sheet except that you add the media type to your <link> element, like so:

<link href="print.css" rel="stylesheet" media="print">

You can test that the print styles are applied by opening the page in a browser and choosing Print Preview.

You write a print style sheet exactly the way you write any other style sheet. However, because it is a style sheet for print, you can use a few styles you otherwise might ignore, such as page-break-before, page-break-after, and page-break-inside. Because web pages don’t have page breaks, these styles aren’t used in screen style sheets.

You can set the media type in any style sheet link with the media attribute. But most designers leave it off because the default is all.

Setting the media type in the <link> tag is not the best way to define styles for media types because it forces the browser to request and load multiple style sheets. The same is true if you use the @import rule. Table 18.1 shows how to use the three different methods to include media queries. The first method is in the HTML, and the other two are right in the CSS document.

Table 18.1 Three Ways to Add Media Queries

Method

Description

<link media="type" href="url" rel="stylesheet">

Use the media attribute on a link tag to define media queries as the style sheet is loaded.

@import url("url") type;

Include the media type in the @import command to define media queries when a style sheet is imported.

@media type { }

Include media-specific styles directly in another style sheet to limit the scope of the enclosed styles.

Best practices are to define styles for different media types all in the same style sheet document, using the @media rule, like so.

  1. Open your style sheet file in a web page editor or text editor.

  2. Add the styles you want to apply to all media types at the top of your style sheet. You do not need any media rules to define them.

  3. Add the media-specific rules with the @media rule. To include a print style sheet, write the following:

    @media print {
      // put print styles here, such as:
      a:link {
        color: black;
        text-decoration: underline;
      }
    }

  4. Include as many different media types as you need. Just remember to include all their styles in a separate curly braces block ({ }).

Note

Requesting multiple CSS documents with the <link> element or @import rule will slow down your website. By keeping your media queries all in one CSS document, you reduce the number of requests to the server, and this improves the speed at which your web pages load. For example, if you have three 1KB CSS files you need to load, if you use @import or <link> tags to include them all, the browser sends three separate requests for each file and has to wait for three responses from the server. If each request and response takes half a second, you’ve added an extra two seconds to the download time for all three files.

Here’s how it would look:

request file 1 (.5s)

response file 1 (.5s)

download file 1 (1KB)

request file 2 (.5s)

response file 2 (.5s)

download file 2 (1KB)

request file 3 (.5s)

response file 3 (.5s)

download file 3 (1KB)

This gives you a total of the time it takes to download 3KB plus 3 seconds of request and response time. If you combine all three files into one 3KB file, you have the same download time (for 3KB) but only one request and response (1s). Yes, 0.5s is an extremely slow request and response, but even fast response times add up. If you have 10 CSS files, plus another 10 JavaScript files, plus other server requests (images, media, and so on), your site will be slowed down considerably.

Using Media Features

CSS media queries get really interesting when it comes to media features. Rather than limit your designs just to specific media types (screen versus print, for example), media features let you look at the specific features of the media and style your pages accordingly.

There are 13 media features you can test for:

  • Image aspect-ratio—A ratio of the width of the device to the height

  • Image color—The number of bits per color component

  • Image color-index—The number of colors in the device’s color input title

  • Image device-aspect-ratio—The ratio of the device width to the device height

  • Image device-height—The height of the rendering surface

  • Image device-width—The width of the rendering surface

  • Image grid—Whether the device is a grid (such as tty devices or phones with only one font) or bitmap

  • Image height—The height of the display area

  • Image monochrome—The number of bits per pixel in monochrome devices; if the device isn’t monochrome, the value will be 0

  • Image orientation—Whether the device is in portrait or landscape mode

  • Image resolution—The pixel density of the device, in print, which would be the dots per inch (dpi) of the printer

  • Image scan—The scanning process of TV output devices, such as progressive scanning

  • Image width—The width of the display area

Caution

The device-width and device-height features are confusing to most web designers at first, as it doesn’t seem like there is any difference between them and the related width and height features, especially on mobile devices. But there is a difference, and it’s important. The width is the width of the browser window, while device-width is the width of the device itself. You can see this most effectively on a computer. When you set a media query with max-device-width and then resize the browser, the page will not change, no matter how much you resize. This is because the device width is the computer monitor, and it doesn’t change.

This may not seem to matter on mobile devices, but on iOS devices, device-width is always the width in portrait mode, even if the device is in landscape. On Android devices, however, device-width (along with device-height and device-aspect-ratio) changes when the device is rotated.

Nearly all the media features also have two prefixes you can use to evaluate: min- and max-. These prefixes evaluate the feature based on whether it is a minimum amount (min-) or a maximum amount (max-). For example, to set a style sheet to apply to all browsers with at least a width of 320px, you would write the following:

@media (min-width: 320px) { ... }

And if you wanted to target devices with browsers no wider than 1024px, you would write this:

@media (max-width: 1024px) { ... }

As you can see, you add the media features to the @media rule with the word and and then enclose your features in parentheses. If you want to get more specific, add more features. For example, to target browsers between 640px and 980px wide, you can write the following:

@media (min-width: 640px) and (max-width: 980px) { ... }

Notice that none of the expressions just mentioned use a media type. That is because if the media type is left off, it applies to all devices, regardless of type.

Using Media Query Expressions

In order to use media queries effectively, you need to know how to write expressions. In the previous section you learned three basic expressions to target browsers above a certain minimum width, to target browsers below a maximum width, and to target browsers that fall between a minimum width and a maximum width. But you can create much more complicated expressions.

Media query expressions use logical operators to define complex scenarios. These are the operators you can use:

  • Image and—This combines features and types together. The query will match if all elements are present. For example, the following would match a device in landscape mode with a 768px browser window:

    @media (min-width: 760px) and (orientation: landscape) { ... }

  • Image Comma-separated list—This is equivalent to the OR logical operator. In a comma-separated list of features or types, if any of them are true, the query will match. For example, this would match both a 480px browser in landscape mode and an 800px browser in portrait mode:

    @media (min-width: 760px), (orientation: landscape) { ... }

  • Image not—This negates the entire query. The query will match if the query would normally return false. For example, the following would match a 480px browser that is in portrait mode:

    @media not (min-width: 760px) and (orientation: landscape) { ... }

Note

The not operator can be confusing to use, but one thing to remember is that it applies only to the entire expression, not individual features. In other words, if you write @media not screen and (max-width:400px), your query will match everything that is both not a screen-based device and that has a width larger than 400px. It helps if you remember to evaluate the not last. So, you write the expression the opposite of what you want and then apply the not operator to the front.

  • Image only—This prevents browsers that don’t support media queries from applying the styles. For example, the following will block extremely old browsers from using the style sheet:

    @media only screen { ... }

Media query expressions are the basis of responsive web design. With them you can define very complex formulas for your style sheets and make sure that the designs look exactly the way you want them to.

What Is a Breakpoint?

A CSS breakpoint is a device feature with a media query declaration assigned to it. They are most commonly based on browser widths, so most designers think of breakpoints as places where the width of the design changes to accommodate different devices.

Most responsive designs have at least one breakpoint that changes the look of the design.

Note

Most experts recommend at least two breakpoints so that your site has three versions: one for small mobile devices, one for midsized tablets, and one for desktop computer screens. But for best results, you should use the breakpoints that are right for your website.

Before you decide that you’re going to have 10 breakpoints or some other arbitrary number, you need to remember that each additional breakpoint adds to the cost of building and maintaining the website. For each breakpoint in your design, you add one more version of the page to style. In other words, you have to style the page even if you have no breakpoints. When you add one breakpoint, you then have a second version of the page to style, and so on.

How to Define Breakpoints in Your CSS

Defining breakpoints is done with CSS media queries. The most common type of breakpoint is based on the width of the device. Listing 18.1 shows the CSS file for a Mobile First site with three breakpoints: one for every browser (the smallest widths), one for widths between 480px and 1200px (larger smartphones and smaller tablets), and one for widths larger than 1200px.

Listing 18.1 A Page with Two Breakpoints

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>A Page with Two Breakpoints</title>
    <style>
      body {
        color: blue;
        font-family: "Handwriting - Dakota", Papyrus;
      }
      @media all and (min-width:480px) and (max-width:1200px){
        body { color: red; }
      }
      @media screen and (min-width:1201px){
        body { color: green; }
      }
    </style>
    <meta name="viewport"
          content="width=device-width,initial-scale=1">
  </head>
  ;<body>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Etiam id purus nec eros semper luctus. Proin nisl lectus,
    ullamcorper ultrices leo in, tristique rutrum risus. Morbi
    congue diam tempor lorem semper, congue tempor turpis pretium.
    Nunc eget dui ut lorem auctor ornare. Vivamus lectus purus,
    vehicula eu velit eu, iaculis ultrices dui. Aliquam consectetur
    risus non ligula blandit, et gravida lectus bibendum. Etiam
    laoreet luctus nibh. Nulla sit amet lorem quis arcu accumsan
    mollis.</p>
  </body>
</html>

Listing 18.1 shows very simple styles that simply change the color of the text depending on the size of the browser—blue for small screens, red for medium-sized screens, and green for large screens. In Figure 18.1 the text is red, and in Figure 18.2 the text is blue.

A screenshot shows the output rendered in Firefox at 1024 pixels wide. The text is in red color.
Figure 18.1 A page viewed in Firefox at 1024 pixels wide.
A screenshot shows Firefox in design mode.
Figure 18.2 A page viewed in Firefox design mode on a 320px-wide device.

Defining the Styles That Remain the Same for Every Device

When you’re writing a style sheet for a responsive website, the first styles you want to define are the ones that are the same no matter what device views them. This is another way of using the Mobile First philosophy. These styles include the following:

  • Image Reset styles

  • Image Colors

  • Image Font families

  • Image Background images

While it’s certainly possible that you could have designs that use different colors, font families, resets, and background images, depending on the device, most websites like to keep a consistent branding. And by keeping these things the same, you reassure your customers that they are on the same page no matter what device they are using.

Listing 18.2 shows a basic style sheet with some initial styles.

Listing 18.2 Initial Styles for a Web Page

@charset "UTF-8";
/* reset styles here */

/* standard colors */
body { background-color: #fff; color: #000; }
h1, h2 { color: #fbd91f;  /* yellow */ }
h3, h4, h5 { color: #000; }

/* standard fonts */
h1, h2, h3 {
  font-family: Baskerville, "Times New Roman", serif;
}
h1 {
  text-shadow:2px 3px 3px #000000;
  margin-bottom: 0.5em;
}
h2 {
  text-shadow: 2px 2px 0 rgba(0,0,0,.5);
  margin-bottom: 0.5em;
}

/* background image on the header */
header {
  width: 100%;
  padding: 0.5em 0 3em 0.25em;
  background-image: url(images/dandy-header-bg.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 0% 100%;
}

While some of the styles set here may be changed for specific devices, this is a good baseline. We set a base font family for our headlines. We gave the document black text and a white background. And we defined a background image for the header. As with any other design, there is always more to do, but this is a start.

Adding Specific Styles for Small Screens

Once you’ve got your basic styles for any machine in the style sheet, you need to add styles specific to the smallest screens. You should put them below your styles for all devices, but not inside a media query. These smallest-screen styles will be overwritten on larger screens by the styles in the media queries because of the CSS cascade.

You should add styles that make your pages as mobile friendly as possible, considering things like the following:

  • Image The width of every content element should be 100% to fill the screen.

  • Image This means you’ll have one column of content.

  • Image Lists, especially lists of links, should have a lot of space between list items, to make them easy to read and click.

Listing 18.3 shows some of the styles added at this stage, and Figure 18.3 shows how this might look on a small-screen phone.

Listing 18.3 CSS Added for Small Screens

/* ######## mobile specific styles ######## */
/* headlines */
h1 { font-size: 2em; }
h2 { font-size: 1.5em; }

/* navigation bar */
nav { width: 100%; background-color: #000; color: #fbd91f; }
nav ul { padding-top: 0.15em; padding-bottom: 0.15em; }
nav ul li { margin: 0 0 0.5em 0.2em; }

/* article */
article { width: 100%; padding: 0.25em; }
article img { width: 100%; height: auto; }

/* aside */
aside { width: 100%; }
aside img { width: 100%; height: auto; }

A screenshot of the Firefox browser in design mode.
Figure 18.3 Viewing a page in Firefox Responsive Design Mode at 320 pixels wide.

Adding Media Queries for Larger Screens

The last thing to add to your style sheet are the media queries with the styles specific to the breakpoints. The Dandylion page shown in Figure 18.3 has two breakpoints: one for medium-sized devices between 481px and 1200px wide and one for large devices with a width bigger than 1201px. Listing 18.4 shows the CSS.

Listing 18.4 Media Queries in the CSS

/* ######## medium sized devices ######## */
@media (min-width: 481px) and (max-width: 1200px) {
}

/* ######## large sized devices ######## */
@media (min-width: 1201px) {
}

Caution

Remember that these style sheets use the cascade to set initial styles and then overwrite them with styles for other devices later in the document. If you aren’t using a WYSIWYG editor or previewing your styles regularly, it can be easy to forget what already has a style. For example, you may set the width of the article element to 100%, but in larger screens you wouldn’t want that as it would make the text lines too long to read. But if you forget to preview the styles at many different browser widths, you could be surprised at the result.

You need to remember the order of your CSS file. Because of the cascade, whatever styles come last will take precedence over styles that came before. So if you style the article element to have 100% width in the first section and then change that to 80% or something else in the medium- or large-sized device media queries, that is the style that will display.

Optimal Breakpoints

RWD beginners commonly wonder what are the best breakpoint numbers. It depends on your customers and your design.

You can use the widths of popular devices to come up with a breakpoint plan that works for your site, but a better solution is to choose breakpoints based on your design. View your site at different widths to see where it breaks. You can use Responsive Design Mode to slowly resize the window until the design breaks. A design is broken when the page is hard to read, content scrolls horizontally, images or text overlaps, or things just look wrong.

Best Practices for Breakpoints

Some of the best practices for choosing the breakpoints include the following:

  • Image Choose breakpoints for the design, not the device—It’s tempting to choose breakpoints for exactly the resolution of the devices you want to support (for example, a min-width of 720px to target iPhone 5S devices). But this is a mistake. It’s better to choose a width based on where your design starts getting difficult to read or use.

  • Image Keep breakpoints 1px different—When you use more than one breakpoint, make sure that the second one is exactly 1px wider or narrower than the first one. In other words, if your smallest breakpoint is for browsers with a width of 480px or smaller, then the next breakpoint should have a minimum width of 481px. If you use the same number for each, this can cause browsers that match that width to use the wrong styles.

  • Image Consider device orientation, not just width—If you have the time and resources, you should consider changing your design based on the orientation of the device and not just the width.

  • Image Don’t forget Retina devices—Pages displayed on Retina displays and other high-pixel-density devices can look bad if your images aren’t optimized for them.

Media Queries for Retina Devices

In Lesson 17, “Designing for Mobile Devices” you learned how to use the srcset and sizes attributes to display different images for different pixel densities. There is also a media query feature that you can use to define styles for high-pixel-density devices. This is the resolution feature. You use it just as you do other features, adding the min- or max- prefixes in your media query. The only browser exception is Safari, which still uses the -webkit-device-pixel-ratio feature.

Retina displays have a 2x pixel ratio, so you can define styles for Retina devices with this media query:

@media (-webkit-min-device-pixel-ratio: 2), /* Safari and iOS */
      (min-resolution: 192dpi)             /* Others */ {
}

You can define higher-density minimum resolutions by changing the dpi you match.

Summary

This lesson introduced you to the meat of responsive web design—media queries with breakpoints. With CSS media queries, you create style sheets that are written explicitly for the devices that you want to define. You can create style sheets only for specific media types or take more granular control with media features. You also learned how to create media query expressions.

You learned what a breakpoint is and how to choose good breakpoints for responsive design. You learned the CSS to create media queries around those breakpoints. And you also learned how to create media queries to detect Retina and other high-pixel-density devices.

Q&A

Q. What’s the difference between CSS2 media queries and CSS3 media queries?

A. CSS2 doesn’t have media queries, but you can define a style sheet for a specific media type. It wasn’t until CSS3 that media queries were developed. Media queries let you define test structures surrounding media types and features that allow only the user agents that fit the query criteria to use the styles.

Q. Why is it important to design for the smallest devices first?

A. Most of the smallest devices are also the least feature rich. In order to build a site using progressive enhancement, you should focus on the minimum you need for the site to work. And that is what you should display to all customers—even those on small-screen devices, as discussed in more detail in Lesson 17, “Designing for Mobile Devices.”

Q. Can I use other media features than just the width to set my breakpoints? Why does everyone only seem to use device widths?

A. The width is the easiest type of breakpoint to understand and test. When you use a minimum or maximum width, you can use your web browser to test your designs by simply resizing the browser window. As long as you’re browsing on a fairly large screen, you can test nearly any device width. It’s a lot harder to test orientation on a desktop computer monitor. But you can use any media feature you need to create the breakpoints that are best for your design.

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. What is the official definition of media query?

2. What is the syntax of a media query?

3. What are five of the media types?

4. What are five of the media features?

5. What are two of the logical operators?

6. How many breakpoints do you need to create a responsive design?

7. What do best practices suggest as the minimum recommended number of breakpoints?

8. What is the CSS for a breakpoint that catches devices 400px and smaller?

9. What is the CSS for a breakpoint to catch all devices between 800 and 1600px wide?

10. What is the media query to detect Retina devices?

Note

Just a reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.informit.com/register and register this book (using ISBN 9780672338083), you can receive free access to an online Web Edition that not only contains the complete text of this book but also features an interactive version of this quiz.

Answers

1. According to the W3C, a media query is a “logical expression that is either true or false. A media query is true if the media type of the media query matches the media type of the device.”

2. The syntax of a media query looks like this:

@media mediaType and (mediaFeature)

3. The 10 media types are all, braille, embossed, handheld, print, projection, screen, speech, tty, and tv.

4. The 13 media features are aspect-ratio, color, color-index, device-aspect-ratio, device-height, device-width, grid, height, monochrome, orientation, resolution, scan, and width.

5. The four operators are and, comma-separated phrases, not, and only.

6. A responsive design usually has at least one breakpoint, but it doesn’t have to have any.

7. Best practices recommend that you have at least two breakpoints to catch small screens, midsized screens, and large screens.

8. This is the CSS for a breakpoint to catch all devices 400px and smaller:

@media screen and (max-width:400px) { }

9. This is the CSS to catch all devices between 800 and 1600px wide:

@media screen and (min-width:800px) and (max-width:1600px) { }

10. This is the media query to detect Retina devices:

@media (-webkit-min-device-pixel-ratio: 2),(min-resolution: 192dpi) { }

Exercises

  • Image Start practicing writing CSS media queries. Look at the site you’ve been evaluating through the book and decide what types of media features you want to focus on for your styles. For example, decide if you need designs for different widths, different orientations, or different aspect-ratios. Your analytics program can help with this by giving you information about what your current customers are using.

  • Image Review the design of the site you’re currently working on in Responsive Design Mode. Resize the window to see where the design breaks and decide what breakpoints you want to use for your design. Then create a CSS style sheet with a media query structure to support those breakpoints. Don’t forget to add to your style sheet CSS styles that apply to all devices, regardless of device size.

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

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