We launched a new IT training category! Check out the 140+ courses now.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Using CSS media queries

From: Mobile Web Design & Development Fundamentals

Video: Using CSS media queries

A little earlier I talked about multi-serving content where you deliver a web page to both a mobile device and a desktop device where the content is just styled appropriately for each one of the form factors. And the way that you accomplish that is by using a technology called CSS media queries which is what we are going to look at now. CSS media queries provide a way of selectively applying style sheets based upon the characteristics of the display media where the content is going to be consumed, whether it's a screen or a printed page or so on.

Using CSS media queries

A little earlier I talked about multi-serving content where you deliver a web page to both a mobile device and a desktop device where the content is just styled appropriately for each one of the form factors. And the way that you accomplish that is by using a technology called CSS media queries which is what we are going to look at now. CSS media queries provide a way of selectively applying style sheets based upon the characteristics of the display media where the content is going to be consumed, whether it's a screen or a printed page or so on.

But what's nice about it is that you can do things like look at the window size or the screen size or whether or not a device is in portrait or landscape orientation, for example, and apply style sheets based upon those kinds of criteria. CSS style sheets are a W3C candidate recommendation as of July 2010, and you can see I have provided the link there to go and learn more about them. But for now let's just go ahead and take a look at the most common stuff that you can do with media queries.

The most common things you want to do with media queries are displayed in this table here, and right at the top you can see there is properties like width and height, and those properties indicate the width and height of an output surface, like a window, of width or height units, pixels, centimeters or whatever. Below that we've got device-width and device-height, and then we've got orientation. These are the most commonly used media query features that you will run across. And for features that use units you can specify any CSS-compliant unit, like pixels, centimeters, inches, ems, so on.

Now the ones I have listed here and many other media query features except a min or max prefix, and the reason you want to do this is because if you use a media query feature like width that basically means target, say, window of exactly width units. So if I said width: 800, the window would need to be exactly that wide in order for a style sheet to apply. So what you typically do is use things like min-width or max-width, and the min prefix and the max prefix will work for everything listed here except for orientation.

Obviously, there is no such thing as min-portrait or max-landscape; you are either in portrait or a landscape. Okay, those are the commonly used ones. Here are some less commonly used ones you might run across, things like aspect ratio, which is the ratio of a display surface's width to its height. So these are typically used on televisions, 4/3 for old TVs, 16/9 for HD TVs, and so on. You can also look at things like color and color-index and what the resolution of the screen is.

And again, you can use the min and max prefixes with all of these except for the scan and grid media query features, but we are not going to focus on these because these are not very commonly used. Okay, let's see how they are used. To use a media query, it's usually used in one of the following situations. Now on the desktop what you typically have is a screen with a window in it, and the window has properties like width and height. And in media queries the width and height properties would refer to the width and height of the window in the desktop context.

And to get the device-width and the device-height you would use those media query features, and that would refer to the screen. Things are a little bit different usually on mobile devices. Mobile devices don't normally have separate windows. The display window that you're seeing is the same size as the screen. So in that case you have a screen size like this and usually height and device-height and width and device- width refer to the same kind of thing. So that's the main difference between using media queries on desktop and devices.

Now to define media queries there's a couple of ways you can do this. You can define a media query directly within a link tag, as you see here where I've got a link tag that's referring to a style sheet, and that bold text there is the media query itself. Now you have probably seen media queries used before without that 'and' clause in there. What it probably usually looks like to you is link rel="stylesheet" and then media= and it will just say, "screen", or it will just say, "print." The and part where it says "and (max-width: 800px)," that's where the query part comes in because the media query is asking the display surface, "Hey, how wide are you?" If you are at maximum width of 800 pixels and the width of the display service is below that right now, then apply at the style sheet.

You can also do it within the CSS style sheet using the @media directive. So in this case I've got an @media directive where it says screen, so I am targeting screens. And the min-width where this style sheet would apply is 801 pixels. So if the screen is greater than 801 pixels wide, or including 801 pixels, then the media query would evaluate to true and the style sheet would apply. Below that level the style definitions contained within those braces would not apply.

You can define multiple CSS media queries for multiple form factors, and I'll show an example of that right here where we have in the first part we have styles to use for small screens, such as phones. And I have a link going to the style sheet. This is media="screen" and the maximum width is 480 pixels. So for screens up to 480 pixels, we would apply the phone.css file. Then for tablets we have the same kind of definition, stylesheet, and in this case the media is screen and the minimum width is 481 pixels and the maximum width is 800 pixels, because most tablets are between 480 and 800 pixels wide--at least when they are in portrait mode. And if that query evaluated to true then we would apply the tablet.css file.

And then finally, for larger screens we would have media="screen" and just a min-width definition of 801 pixels. So for screens that were wider than 801 pixels, or I should say 801 pixels or wider, we would just include the styles.css file. So the actual question might be, should you use width or should you use device-width? Well, the width and device-width properties mean slightly different things. The width property refers to the current display surface and on a desktop that means the window.

The device-width property refers to whatever the screen display size is. So what that means is on a desktop where the window can be different than the screen, the width property can change. The device-width property doesn't typically change. The general guidelines to follow are this. If your style sheet is going to be used both on desktop and mobile devices, use the width property since on desktops the display service width can change.

If your style sheet is only going to be used on a mobile device, you can use the device-width property, but generally speaking I just use the width property because it's sufficient for most needs. Okay, let's take a look at how this works in real code. Okay, so here I am in the code, and I have got my mediaqueries_start example file open, and this is the HTML version. I have also got mediaqueries_start, the CSS file, and I've got my ExampleSnippets.txt file. So let's begin by taking a look at the mediaqueries_start file.

You can see that here's the code, and let me show you what this looks like in a browser. So here's the file in a desktop browser, and you can see that as I change the width, nothing is happening, and I am just getting the same content when it's flowing, and that's not the experience I would like to have. Let me show you what the finished example looks like. Okay, so here is the finished example. You'll notice that as I change the width of the window down to about 800 pixels, something is happening there, so you see that the links are going horizontal instead of being vertical like they are here.

The title space is changing both right alignment and background color and foreground color, and you can see down here that there is a footer, and the footer in this page looks a little bit different than it does in the other page. So let's see how we got that to happen. So here in my start.html file I've got a mediaqueries_start.css file that I am including. So what I am going to do is go over to the media query CSS file and I am going to go to my snippets and I am going to copy this code right here.

I am going to copy @media screen and (min-width: 801px). I am going to paste that in up here, and I'll put the closing brace down here. Okay, so what I have done is defined a media query where I'm looking at a screen, media, and the minimum width that these style rules have to apply is when the screen is 801 pixels or larger. So when the window is that wide or larger the rules contained within this media block will apply.

Let's go back to the snippets. Now I am going to copy the other media query, and that's this code right here, all the way down to the last brace, and I will copy that and I will paste it below this one. So now, I've essentially got two media queries: one where I'm looking at the minimum width is 801 pixels or larger and then another one where the rules apply for the screen where the maximum width is 800 pixels.

So if the window width is 800 pixels or less, these rules apply; otherwise the other rules apply. I am going to save this, and I am going to make sure this saved as well. And now I am going to go back out to the file system, and I'll start up mediaqueries_start, and we will refresh this and we will go ahead and change. And you can see that now as I am changing the window size, you can see that the layout is changing. Okay, now let's make sure that this is working in our mobile emulators. Okay, so now what I am going to do is copy the files that I just edited over to my web server.

So I will copy them in here, and now I will try it out in my emulators. So let's try it out in the mobile Opera emulator first, and we will do the localhost/exercise_files. And you can see that because the screen width is less than 800 pixels, the style sheet for the small size is being applied. Let's try the same thing in the Windows Phone emulator, localhost, and we are getting the same results over here.

So that in a nutshell is how you use media queries to change how style sheets are applied based upon the physical characteristics of the device that the content is being rendered on.

Show transcript

This video is part of

Image for Mobile Web Design & Development Fundamentals
Mobile Web Design & Development Fundamentals

46 video lessons · 25043 viewers

Joe Marini
Author

 
Expand all | Collapse all
  1. 2m 48s
    1. Welcome
      1m 2s
    2. Using the exercise files
      1m 46s
  2. 29m 25s
    1. Understanding the mobile context
      8m 5s
    2. A survey of mobile sites
      11m 44s
    3. Targeting mobile browsers
      4m 31s
    4. Previewing a complete mobile site
      5m 5s
  3. 27m 20s
    1. Designing for one web
      3m 43s
    2. Using well-defined web standards
      3m 45s
    3. Designing mobile-friendly pages
      3m 40s
    4. Being crisp, clean, and succinct
      5m 45s
    5. Minimizing input where possible
      6m 47s
    6. Focusing on the core scenarios
      3m 40s
  4. 1h 13m
    1. Installing the tools
      3m 52s
    2. Setting up a local web server
      9m 13s
    3. Installing device emulators
      17m 5s
    4. Using device emulators
      13m 9s
    5. Downloading Modernizr and Mobile Boilerplate
      6m 22s
    6. Building a first mobile web page
      5m 43s
    7. Developing mobile pages with desktop browsers
      8m 6s
    8. Exploring useful mobile web development resources
      10m 23s
  5. 53m 26s
    1. Reviewing mobile markup languages
      5m 10s
    2. Understanding content adaptation approaches
      10m 32s
    3. Controlling the viewport layout
      12m 50s
    4. Designing forms
      13m 30s
    5. Using CSS media queries
      11m 24s
  6. 1h 11m
    1. Detecting client capabilities with script
      10m 8s
    2. Caching information with local storage
      9m 16s
    3. Determining position with geolocation
      12m 52s
    4. Minimizing HTTP requests with data URLs
      7m 39s
    5. Understanding user agent detection
      9m 8s
    6. Using server-side detection with PHP
      6m 52s
    7. Using server-side detection with ASP.NET
      4m 54s
    8. Using HTML5 Boilerplate for mobile
      11m 6s
  7. 39m 22s
    1. Measuring performance
      7m 41s
    2. Creating full-screen web apps
      6m 30s
    3. Customizing the user interface
      5m 14s
    4. Detecting orientation changes
      3m 58s
    5. Detecting device movement
      5m 21s
    6. Using touch events
      10m 38s
  8. 47m 14s
    1. Taking a look at the finished site
      7m 40s
    2. Examining the header and background image style on the Home page
      10m 10s
    3. Examining the hover effect and layout styles on the Tours page
      6m 42s
    4. Examining mobile forms on the Contact page
      9m 45s
    5. Viewing and testing the mobile site on emulators
      8m 11s
    6. Viewing the site on devices
      4m 46s
  9. 2m 34s
    1. Goodbye
      2m 34s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Mobile Web Design & Development Fundamentals.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.