Media Queries

Intro to Responsive Design Patterns

Intro to Media Queries

Linked Style Sheet Media Query

In this first video, you will learn about using the link tag in HTML to import style sheets when a certain condition is true about the media in question.

So, following from their examples, the below HTML code for a linked style sheet media query would only load that style sheet when the screens width was larger than 500px.

HTML
<link rel="stylesheet" media="screen and (min-width: 600px)" href="style-min-600.css">

Likewise, the following would only load the style-499-max.css stylesheet when the screen size is less than or equal to 499px.

HTML
<link rel="stylesheet" media="screen and (max-width: 499px)" href="style-max-499.css">

Most Common Media Queries

The most common media queries are

min-width:

Which is executed with the pixel amount is greater than the set number.

max-width:

Which is executed when the browser is less than the number of pixels specified.

Media Query Example 1

In the following example, there are three style sheets;

  • main.css
    • Always loaded and active
    • This sets the font family to sans-serif
    • And makes the body elements default background-color white.
  • 499-max.css
    • This is only loaded if the window width is less than 500 pixels.
    • This changes the background color to red.
  • 600-max.css
    • This is only loaded and active if the window width is greater than 600 pixels.
    • This changes the background color to blue.

Notice how they allow the examples background color to change, based on the screen size of the iframe. You should also open this example in a separate tab to explore it in your own browser directly.

HTML
<head>
    <meta charset="utf-8">
    <title>Media Query Example 1</title>

    <!-- Main CSS Style Sheet -->
    <link rel="stylesheet" href="./css/main.css">

    <!-- CSS Style Sheets loaded via media queries -->
    <link rel="stylesheet" media="(min-width:600px)" href="./css/600-min.css">
    <link rel="stylesheet" media="(max-width:499px)" href="./css/499-max.css">

</head>
<body>
    <h2>Media Query Example.</h2>
    <h3>Please resize your browser. You Should see the background color change.</h3>
    <h3>You might also open the example in a seperate tab, via the link below.</h3>
</body>
CSS (main.css)
body {
    font-family: sans-serif;
    background-color: #fff;
}
CSS (499-max.css)
body {
    background-color: #ff0000;
}
CSS (600-min.css)
body {
    background-color: #0000ff;
}
[Code Download] [View on GitHub] [Live Example]

Previous section: