• 20 heures
  • Facile

Ce cours est visible gratuitement en ligne.

Vous pouvez obtenir un certificat de réussite à l'issue de ce cours.

Vous pouvez être accompagné et mentoré par un professeur particulier par visioconférence sur ce cours.

J'ai tout compris !

Mis à jour le 12/11/2018

Adaptive page layout with Media Queries

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

Do you know what webmasters implementing their website's design are most concerned about? Their visitors' screen resolution. Indeed so: the space or number of pixels wide various from one screen to another.

This information is important when you build a design: how should your website be displayed for different screen resolutions? If you have a wide screen, you may forget that some people browse with smaller screens. Not to mention the browsers of smart phones, which are even less wide.

This is where media queries come in. These are the rules to be applied to change the design of a website based on the screen's characteristics! Using this technique, we can create a design that automatically adjusts to each visitor's screen!

Implementation of media queries

Media queries are part of CSS3's new features. They are not new properties but rather rules that can be applied under certain conditions. Specifically, you'll be able to say, "If the visitor's screen's resolution is less than a certain value, then apply the following CSS properties". This allows you to change the website's appearance under certain conditions: You can increase the text size, change the background color, position your menu differently with certain resolutions, etc.
Contrary to what one might think, media queries are not just about screen resolutions. You can change your website's appearance based on other criteria such as screen type (smart phone, TV, projector, etc.), the number of colors, the screen orientation (portrait or landscape), etc. There are a great number of possibilities!

Applying a media query

Media queries are thus rules that specify when CSS properties have to be applied. There are two ways to use them:

  • by loading a different .css stylesheet based on the rule (e.g. "If the resolution is less than 1280px wide, load the small_resolution.css") file;

  • by writing the rule directly in the usual .css file (e.g. "If the resolution is less than 1280px wide, load the CSS properties below").

Loading a different stylesheet

You remember the <link /> tag which, in our HTML code, loaded a .css file?

<link rel="stylesheet" href="style.css" />

You can add a media attribute, in which we're going to write the rule to be applied for the file to be loaded. This is known as making a media query. For example:

<link rel="stylesheet" media="screen and (max-width: 1280px)" href="small_resolution.css" />

In the end, your HTML code may provide several CSS files: one as default (which is loaded in all cases) and one or two others which are only charged in addition if the corresponding rule applies.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" /> <!-- For everyone -->
        <link rel="stylesheet" media="screen and (max-width: 1280px)" href="small_resolution.css" /> <!-- For those who have a resolution lower than 1280px -->
        <title>Media queries</title>
    </head>
Loading rules directly in the style sheet

Another technique, which I personally prefer for practical reasons, is to write these rules in the same CSS file as usual.
In this case, we write the rule in the .css file like this:

@media screen and (max-width: 1280px)
{
    /* Write your CSS properties here ici */
}

The available rules

There are many rules for building media queries. I'll only mention the main ones here:

  • color: color management (in bits/pixel).

  • height: display field height (window).

  • width: display field width (window).

  • device-height: device height.

  • device-width: device width.

  • orientation: device orientation (portrait or landscape).

  • media: output screen type. A few of the possible values:

    • screen: "conventional" screen;

    • handheld: mobile device;

    • print: printing;

    • tv: television;

    • projection: projector;

    • all: all types of screens.

The rules can be combined using the following words:

  • only: "only";

  • and: "and";

  • not: "not";

Here are a few examples of media queries to help you understand the principle.

/* On screens with a maximum window width of 1280px */
@media screen and (max-width: 1280px)

/* On all screen types with a window width of between 1024px and 1280px */
@media all and (min-width: 1024px) and (max-width: 1280px)

/* On TVs */
@media tv

/* On all vertically oriented types of screens */
@media all and (orientation: portrait)

Testing media queries

Media queries are mostly used to adapt the website design to different screen widths.

Let's do a very simple test: we're going to change the text size and color if the window is more or less than 1024 pixels wide. For this test, I'm going to use the second method is to write the rule directly in the same .css file as usual:

/* Paragraphs blue as default */
p
{
    color: blue;
}

/* New rules if the window width is smaller than 1024px */
@media screen and (max-width: 1024px)
{
    p
    {
        color: red; 
        background-color: black;
        font-size: 1.2em;
    }
}

In our CSS, we first asked for the paragraph text to be written in blue. So far nothing new. However, we have added a media query that applies to all screens not wider than 1024px. Inside, we applied CSS rules to paragraphs to write them bigger and in red.

Result: the page appearance varies according to the window size (figure below)! 

The page appearance varies according to the window size

Practical use of media queries in the design

Well, changing the text color is nice but it doesn't really add much. However, using media queries to change your website's appearance depending on screen resolution is immediately much more useful. You'll see that you can do whatever you want!

For this example, I suggest you reuse the design we created for the Zozor website (figure below).

The website built during the practical example
The website built during the practical example

Although the website is suitable for most screen resolutions, you have to "scroll" it to the right to see the whole page when the screen is smaller than 1024 px. The website is not very convenient to see on a small screen.

I suggest you use media queries to change the website's appearance for resolutions less than 1024 px wide. We're going to make the following changes:

  • the browsing menu at the top right will be arranged height-wise rather than width-wise, and the links will be written in smaller characters;

  • the banner with the San Francisco bridge (the Golden Gate) Will be deleted as it takes up a lot of space and doesn't provide much information;

  • the "About the author" <aside> block will be placed under the article (rather than next to it), and its content will be reorganized (the Zozor photo be have a floating position).

You could of course make a lot of other changes: change the color, the footer arrangement, etc. But this will already be more than enough to give us some practice with media queries.

We're going to work directly inside thestyle.css file we produced during the practical example and add a few media queries instructions to adjust the design. I suggest you download the practical example files if you haven't done so already.

Download the practical example

The page

The page width is currently set to 900 px and the content is centered:

#bloc_page
{
    width: 900px;
    margin: auto;
}

I suggest you add the following media query rule after these lines:

@media all and (max-width: 1024px)
{
    #bloc_page
    {
        width: auto;
    }
}

This rule means: "if the window width does not exceed 1024 px then run the following CSS rules for all screen types".

The CSS rules in question are very simple; there's actually only one rule: the page wide is adjusted automatically (rather than given a fixed width of 900 px). The page will then take up all the available space in the window. This avoids the appearance of horizontal scrollbars with low resolutions.

The browsing menu

We want the browsing menu to take up less space on smaller resolution screens. Rather than giving it a fixed size, we're going to restore its original automatic flexible size. Each menu item is written underneath the previous one: for this purpose, we'll convert the bullets into block tags rather than inline-block.

Finally, the text will be written smaller and the border at the bottom of the links will be removed when hovering, as it's less suitable with such a screen arrangement.

@media all and (max-width: 1024px)
{
    nav
    {
        width: auto;
        text-align: left;
    }
    
    nav li
    {
        display: block;
        padding-left: 4px;
    }
    
    nav a
    {
        font-size: 1.1em;
    }
    
    nav a:hover
    {
        border-bottom: 0;
    }
}

The banner

To remove the banner, nothing could be simpler: we use the display property assigning it with the value none. If the window is too small, it may be preferable to hide the banner completely:

@media all and (max-width: 1024px)
{
    #banner_image
    {
        display: none;
    }
}

The "About the author" block

Rather than placing this block on the right of the article, we're going to position it underneath. This type of "top-down" arrangement is more suitable for small screens.

We'll slightly readjust the position of the items slightly, inside the block: in particular, the photo of Zozor will be placed in a floating position on the right.

@media all and (max-width: 1024px)
{
    article, aside
    {
        width: auto;
        display: block;
        margin-bottom: 15px;
    }
    
    #arrow
    {
        display: none;
    }
    
    #zozor_picture img
    {
        width: 110px;
        float: right;
        margin-left: 15px;
    }
    
    aside p:last-child
    {
        text-align: center;
    }
}

What's the meaning of aside p:last-child?

It's an advanced selector we haven't used so far. aside p means "All paragraphs inside the tag <aside>". :last-child targets only the last paragraph in the aside block (which contains the links to Facebook and Twitter), so as to center the images. Of course, you could have assigned a class or an id to this paragraph to target it directly, but I didn't want to change the HTML code.

The result

The page will now be completely reorganized when the window is 1024 px wide or less. You can see the results in the figure below, which speaks for itself!

The same website, shown differently according to screen width

The same website, shown differently according to screen width

Media queries and mobile browsers

As you probably know, the screens of smart phones are much narrower than our usual computer screens (they're only a few hundred pixels wide). To adapt to this, mobile browsers display the website by "zooming out" to allow the whole page to be seen. The simulated display area is called the viewport: it's the width of the mobile phone's browser window.

With media queries, if, in CSS, you target the screen with max-width on a mobile phone, it will compare the width you specify against the width of its viewport. The problem is that the viewport changes according to the mobile browser used!

Browser

Default viewport width

Opera Mobile

850 pixels

iPhone Safari

980 pixels

Android

800 pixels

Windows Phone 7

1024 pixels

An iPhone behaves as if the window were 980 px wide, while an Android behaves as if the window were 800 px wide!

To target smart phones, it may be better, rather than using max-width, to use max-device-width: this is the device's width. Mobile devices are not more than 480 px wide, so we can target mobile browsers only, using this media query:

@media all and (max-device-width: 480px)
{
    /* Your CSS rules for your mobile phones here */
}

Why not target mobile phones using the handheld media rule?

I can see that you're following: very good! Indeed, we could theoretically target mobile screens using the handheld media rule... Unfortunately, no mobile browser except Opera mobile recognizes handheld. They all behave as if they were normal screens (screen). So you can't really use handheld for mobile phones.

You can change the mobile browser's viewport width with a meta tag to be inserted in the document header (<head>):

<meta name="viewport" content="width=320" />

You can use this tag to change the way your page content is organized on mobile phones. To obtain readable render without zooming, you can set the viewport to the same width as the screen:

<meta name="viewport" content="width=device-width" />

Summing up

  • Media queries allow the loading of various CSS styles based on certain settings.

  • There are a large number of settings allowed by media queries: number of colors, screen resolution, orientation, etc. In practice, they are mostly used to change the website's appearance for different screen resolutions.

  • You create a media query with the @media directive followed by the screen type and one or more conditions (such as the maximum screen width). The following CSS style will be enabled only if the conditions are met.

  • Mobile browsers simulate a screen width: this is called the viewport.

  • Smart phones can be targeted by a rule based on the actual number of pixels displayed on the screen: max-device-width.

Exemple de certificat de réussite
Exemple de certificat de réussite