facebook twitter
Webucator's Free Introduction to CSS Tutorial

Lesson: Media Queries

Welcome to our free Introduction to CSS tutorial. This tutorial is based on Webucator's Introduction to CSS Training course.

In this lesson, you will learn to work with media queries.

Lesson Goals

  • Understand what media queries are.
  • Use Font Awesome.
  • Understand and use media queries to create breakpoints.
  • Understand and use media queries to target media types.

What Are Media Queries?

Media queries are essentially conditionals that check for media features and allow us to style our pages based on those features. With the advent of mobile devices like smartphones and tablets, it became important to target these different devices to create websites that worked for them. Media queries were essential to this process as they can be used to specify styles based on more than a dozen different media features (https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features) (e.g., aspect-ratio, resolution, orientation, resolution, etc.). However, with the development of more flexible layouts like Flexible Box Layout Module (https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox) and Grid Layout (https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Grids), it has become less important to use all of these features to target specific devices. Instead, it is recommended to use media queries to add breakpoints where your design breaks.

Breakpoints

Breakpoints are specified width lengths where your layout changes to accommodate the larger or smaller viewport. Breakpoints should be based on your design and content and not on specific devices. You want to target the widths where things start to go wrong in your layout (e.g., elements overlap or become too small, lines become too long to read comfortably, a lot of extra space is available, etc.).

Media Types

Media queries can also be used to style pages for different media types (https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#Media_types). A common example of this is creating a different design for how a website looks when it is printed. This may include removing darker background colors, removing unnecessary images and advertisements, adjusting the font to be better suited for printing, etc.

Syntax

Media queries are performed using the @media at-rule. The syntax is below:

Syntax

@media media-type {
  /* rules for specified media type 
    (e.g., print) */
}
  /* OR */
@media (media feature condition) {
  /* rules for specified media feature condition 
    (e.g., max-width: 500px ) */
}
  /* OR */
@media media-type and (media feature condition) {
  /* rules for specified media-type 
    and media feature condition */
}

Font Awesome

Font Awesome provides a collection of free vector icons that you can use on your websites. You can get access to these icons through a free content delivery network (CDN). To do so, you need to go to their website to get a <script> tag with a kit code, which will looks something like this:

<script src="https://kit.fontawesome.com/kit-code.js"></script>

You will have to replace kit-code in the above tag with the kit code they send you.

To get the <script> tag with your unique kit code for your project:

  1. Go to https://fontawesome.com.
  2. Click the Start menu item at the top of the page.
  3. Enter your email address and follow the directions they give you. You will need to create an account with a password, but you should not need to provide further personal details.
  4. Paste the script element into the head of your HTML:
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="../normalize.css">
    <link rel="stylesheet" href="../styles.css">
    <script src="https://kit.fontawesome.com/kit-code.js"></script>
    <title>Font Awesome</title>
    </head>

Finding and Using Icons

To find Font Awesome icons:

  1. Use the search feature at https://fontawesome.com/icons: Font Awesome Search
  2. Click on the icon you want to use.
  3. Click on the HTML code snippet on the icon page to copy it:Font Awesome Copy
  4. Then paste that code snippet wherever you want the icon to show up.

Below is a page containing several Font Awesome icons:

Code Sample:

MediaQueries/Demos/font-awesome.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<script src="https://kit.fontawesome.com/f804978a2a.js"></script>
<title>Font Awesome</title>
</head>
<body class="webucator">
<main>
  <i class="fas fa-phone"></i>
  <i class="fas fa-envelope-square"></i>
  <i class="fas fa-search"></i>
  <i class="fab fa-grunt"></i>
  <i class="fab fa-facebook"></i>
  <i class="fas fa-chevron-up"></i>
  <i class="fas fa-chevron-down"></i>
</main>
</body>
</html>

Code Explanation

The icons on this page are shown below: Font Awesome Icons Open MediaQueries/Demos/font-awesome.html in your browser to see the web page.

Breakpoints

Duration: 10 to 20 minutes.

Let's look at how we could use a media query to create a breakpoint between a laptop menu layout and a mobile layout.

We are going to replace a standard horizontal menu with a vertical mobile menu that shows up when the user hovers over the Font Awesome bars icon (https://fontawesome.com/icons/bars?style=solid).

Here is the standard horizontal menu we are starting with: Breakpoints Laptop Menu

Here is the vertical mobile menu that is hidden, so only the bars icon is showing: Breakpoints Mobile Menu Icon

Here is the vertical mobile menu being shown: Breakpoints Mobile Menu

Follow these steps:

  1. Open MediaQueries/Exercises/breakpoints-styles.css and MediaQueries/Exercises/breakpoints.html in your editor.
  2. At the bottom of MediaQueries/Exercises/breakpoints-styles.css create the @media rule targeting viewports no larger than 460px (@media (max-width: 460px)).
  3. Create a rule that displays the bars icon in the top left corner of the document.
    1. Make the cursor (https://developer.mozilla.org/en-US/docs/Web/CSS/cursor) be a pointer when the mouse is on the bars icon (cursor: pointer).
    Breakpoints Step 2
  4. Create a rule that gets rid of the float on the li elements. Breakpoints Step 3
  5. Style the nav ul.
    1. Make the background white.
    2. Position it so that it covers "Background", but not the bars icon.
    3. Make the width 100%.
    Breakpoints Step 4
  6. Uncomment line 12 in the HTML. This links to a JavaScript file called breakpoints-script.js that allows you to toggle the mobile menu by clicking on the bars icon. Also, set the display of the nav ul to none, so that, by default, it doesn't show up in the mobile view.
  7. Create a rule that centers the a elements in their li elements. Breakpoints Step 6
  8. Create a rule that makes font size in the nav larger. Breakpoints Step 7

You can see the final code below:

Solution:

MediaQueries/Solutions/breakpoints-styles.css
body {
  background: aliceblue;
}

nav {
  background: white;
  margin: 0 -0.5rem;
}

#mobile-menu-icon {
  display: none;
}

nav::after {
  content: "";
  display: block;
  clear: both;
}

nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

nav li {
  float: left;
}

nav a {
  display: block;
  padding: 1rem;
  text-decoration: none;
}

nav a:hover {
  background: rgb(240, 240, 240);
}

nav a:active {
  color: #cce;
}

@media (max-width: 460px) {
  #mobile-menu-icon {
    cursor: pointer;
    display: block;
    left: 0.1rem;
    position: absolute;
    top: 0.1rem;
  }

   nav {
    font-size: 1.2rem;
  }

  nav ul {
    background: white;
    display: none;
    position: absolute;
    top: 1.3rem;
    width: 100%;
  }

  nav li {
    float: none;
  }
  
  nav a {
    text-align: center;
  }
}

Solution:

MediaQueries/Solutions/breakpoints.html
---- C O D E   O M I T T E D ----
<link href="breakpoints-styles.css" rel="stylesheet">
<script src="breakpoints-script.js"></script>
<!-- You may need to replace the tag below using your font awesome key code. -->
<script src="https://kit.fontawesome.com/f804978a2a.js"></script>
<title>Breakpoints</title>
</head>
<body class="webucator">
<h1>Breakpoints</h1>
<nav>
  <i id="mobile-menu-icon" class="fas fa-bars"></i>
  <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="services.html">Services</a></li>
    <li><a href="products.html">Products</a></li>
    <li><a href="blog.html">Blog</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="contact.html">Contact</a></li>
  </ul>
</nav>
</body>
</html>

Targeting Print

Duration: 10 to 20 minutes.

Let's look at how we might use a media query to change the print design of a web page.

Here we have a page called Recipe Master that is opened to a recipe for "Classic Scrambled Eggs": Print Demo Website

This is how the page currently looks in print preview mode: Print Demo Before

Following these steps, make it look like the image below: Print Demo After

  1. Open MediaQueries/Exercises/print-styles.css and MediaQueries/Exercises/print.html in your editor.
  2. At the bottom of MediaQueries/Exercises/print-styles.css create the @media rule targeting print.
  3. Add a rule that makes the title h1, header, footer, aside, and recipe-photo img disappear (display: none). Print Demo Step 2
  4. Add a rule that turns the orange and off-white colors to white, which is better for printing. Print Demo Step 3
  5. Add a rule that makes the print-callout div appear. Print Demo Step 4

Solution:

MediaQueries/Solutions/print-styles.css
body {
  background: rgb(219, 158, 44);
}

h1.title {
  background: url(images/veggies.png) left/contain;
  color: rgb(240, 181, 72);
  padding: 2em 1em 0.2em;
  margin: -1rem -0.5rem 0;
  text-shadow: 0 0 0.2rem blue;
}

header {
  background: lightgray;
  padding-right: 1rem;
  margin: 0 -0.5rem;
  width: 100%;
}

nav ol {
  list-style: none;
  margin: 0;
  padding: 0;
}

nav ol li {
  float: left;
}

nav ol li.contains ol {
  background: lightgray;
  display: none;
  font-size: smaller;
  position: absolute;
}

nav ol li.contains:hover ol {
  display: block;
}

nav ol li ol li {
  float: none;
}

nav::after {
  content: "";
  display: block;
  clear: both;
}

nav a {
  display: block;
  padding: 1rem;
  text-decoration: none;
}

nav li:hover {
  background: rgb(209, 181, 148);
  transition: background 0.4s;
}

nav a:active {
  color: red;
}

main {
  background: rgb(219, 218, 218);
  margin: 0 auto 0;
  padding: 0.2rem 1rem 1rem;
  width: 95%;
}

.subtitle {
  font-style: italic;
}

.recipe-photo {
  width: 300px;
}

section,
aside {
  background: whitesmoke;
  padding: 0.1rem 0.4rem 0.4rem;
  margin: 0 auto 0.4rem;
}

aside {
  border: solid blue;
  border-radius: 0.5rem;
  width: 90%;
}

aside::after {
  content: "";
  display: block;
  clear: both;
}

aside div {
  float: left;
  width: 33.3%;
}

aside div a {
  display: block;
  width: 100%;
}

aside div img {
  width: 100%;
  transition: transform 0.5s;
}

aside div img:hover {
  transform: scale(0.95);
  transition: transform 0.5s;
}

footer {
  background: lightgray;
  font-size: medium;
  font-style: italic;
  min-width: 640px;
  margin: 0 auto;
  padding: 0.2rem 1rem;
  width: 95%;
}

footer::after {
  content: "";
  display: block;
  clear: both;
}

footer h2 {
  margin: 0;
}

footer a.image {
  margin: 0.2rem;
}

footer a {
  text-decoration: underline;
}

footer p {
  float: right;
}

.print-callout {
  display: none;
}

@media print {
  h1.title,
  header, 
  footer, 
  aside,
  img.recipe-photo {
    display: none;
  }

  body,
  main,
  section {
    background: white;
  }

  .print-callout {
    display: block;
    font-size: medium;
    font-style: italic;
    text-align: right;
  }
}

Solution:

MediaQueries/Solutions/print.html
---- C O D E   O M I T T E D ----
<body class="webucator">
<h1 class="title">Recipe Master - Styling for Print</h1>
<header>
  <nav>
    <ol>
      <li><a href="index.html">Home</a></li>
      <li><a href="recipes.html">Browse Recipes</a></li>
      <li><a href="my-account.html">My Account</a></li>
    </ol>
  </nav>
</header>
<main>
  <h2>Classic Scrambled Eggs</h2>
  <p class="subtitle">
    Classic scrambled eggs are the best scrambled eggs!
  </p>
  <img class="recipe-photo" 
  src="images/scrambled-eggs.jpg" alt="Classic Scrambled Eggs">
  <section class="ingredients">
    <h3>Ingredients:</h3>
    <ul>
      <li>Eggs</li>
      <li>Milk</li>
      <li>Butter</li>
      <li>Red Peppers</li>
      <li>Onions</li>
      <li>Salt</li>
      <li>Pepper</li>
      <li>Cheese</li>
    </ul>
  </section>
  <section class="instructions">
    <h3>Instructions:</h3>
    <ol>
      <li>Crack eggs into bowl.</li>
      <li>Add milk and beat until mixed smoothly.</li>
      <li>Put the pan to medium heat. Coat pan with a thin layer of butter.</li>
      <li>Fry the red peppers and onions until they look ready, and then pour the eggs on top.</li>
      <li>Sprinkle a bit of salt over everything.</li>
      <li>With spatula or fork stir the eggs consistently from the middle.</li>
      <li>When the eggs looks ready, turn off the heat and throw some cheese, pepper and salt on top of the eggs.</li>
      <li>Serve and you are done!</li>
    </ol>
  </section>
  <aside>
    <h3>Check out some similar recipes!</h3>
    <div>
      <a href="recipemaster.com/recipes.html#fried-eggs">
        <img src="images/fried-eggs.jpeg" alt="Fried Eggs">
      </a>
    </div>
    <div>
      <a href="recipemaster.com/recipes.html#hard-boiled-eggs">
        <img src="images/hard-boiled-eggs.jpeg" alt="Hard Boiled Eggs">
      </a>
    </div>
    <div>
      <a href="recipemaster.com/recipes.html#pancakes">
        <img src="images/pancakes.jpeg" alt="Pancakes">
      </a>
    </div>
  </aside>
</main>
<footer>
  <h2>Connect with us!</h2>
  <a class="image" href="https://www.facebook.com/">
    <img alt="Facebook Logo" src="images/facebook-logo.png"></a>
  <a class="image" href="https://www.instagram.com/">
    <img alt="Instagram Logo" src="images/instagram-logo.png"></a>
  <a class="image" href="https://twitter.com/">
    <img alt="Twitter Logo" src="images/twitter-logo.png"></a>
  <a class="image" href="https://www.pinterest.com/#">
    <img alt="Pinterest Logo" src="images/pinterest-logo.png"></a>
  <p>&copy; 2020 Recipe Master. All rights reserved.
  For questions, send email to
<a href="mailto:info@recipemaster.example.com">info@recipemaster.example.com</a>.</p>
</footer>
<div class="print-callout">
  <p>Check out more great recipes at <a href="recipemaster.example.com">recipemaster.example.com</a>!</p>
</div>
</body>
</html>