CSS3 media queries and page adaptation

In September 2017, W3C released the Media Query Level 4 Candidate Recommendation Standard Specification, which expands the functions of already released media queries. This specification is used for the @media rules of CSS, which can set the style of specific conditions for documents, and can also be used for HTML, JavaScript and other languages.

1. Basics of media query

Media queries can define independent CSS style sheets for devices based on device characteristics, such as screen width, height, and device orientation (landscape or portrait). A media query consists of an optional media type and zero or more scoped expressions, such as width, height, and color.

1.1, media types and media queries

CSS2 introduces the concept of media type, which allows setting a limited range of media types for style sheets. For example, style sheet files only for printing, style sheet files only for mobile phone rendering, style sheet files only for TV rendering, etc. The specific description is as shown in the following table:

Define the media type of the style sheet through the media attribute of the HTML tag. The specific method is as follows:

  • Defines the media type for external style sheet files.
  • Defines the media type of the internal style sheet file.

    CSS3 proposes the concept of Media Queries based on media types. Media queries are more powerful and complete than CSS2 media types. The main difference between the two: media queries are a value or a range of values, while media types are just device matches. Media types can help users obtain the following data.

  • The width and height of the browser window.
  • The width and height of the device.
  • The orientation of the device, whether horizontal or vertical.
  • resolution.

For example, the following statement imports an external style sheet:

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

Set the conditions of the media query in the media attribute (max-width: 600px): when the screen width is less than or equal to 600px, the small.css style sheet is called to render the page.

1.2, using @media

CSS3 uses @media rules to define media queries. The simplified syntax format is as follows:

 @media [only | not]? <media_type> [and <expression>]* | <expression> [and <expression>]*{<!-- -->
        /* CSS style list */
    }

The parameters are briefly described as follows:

  • : Specify the media type. For specific instructions, refer to the table above.
  • : Specifies media characteristics. Put it in a pair of parentheses, such as (min-width:400px).
  • Logical operators, such as and (logical AND), not (logical NO), only (compatible devices), etc.

Media properties include 13 types, receiving a single logical expression as a value, or no value. Most features accept the prefix min or max to indicate greater than equal to or less than equal to logic, thereby avoiding the use of the greater than (>) and less than (<) characters.

The @media keyword must be defined at the beginning of the CSS style, then specify the media type, and then specify the media characteristics. The format of media properties is similar to that of styles, divided into two parts, separated by colons. The media properties are specified before the colon, and the value of the property is specified after the colon.

[Example 1] The following statement specifies the style used when the device display screen width is less than 640px:

 @media screen and (max-width: 639px) {<!-- -->
        /*Style code*/
    }

[Example 2] You can use multiple media queries to apply the same style to different media types and media attributes. The media queries are separated by commas, similar to selector grouping:

 @media handheld and (min-width:360px),screen and (min-width:480px) {<!-- -->
        /*Style code*/
    }

[Example 3] You can add logical operators such as not, only, and and to the expression:

 //The following style code will be used in devices other than portable devices or non-color portable devices
    @media not handheld and (color) {<!-- -->
        /*Style code*/
    }
    //The following style code will be used in all non-color devices
    @media all and (not color) {<!-- -->
        /*Style code*/
    }

[Example 4] The only operator allows devices that do not support media queries but support media types to ignore the style in the expression. For example:

 @media only screen and (color) {<!-- -->
        /*Style code*/
    }

For devices that support media queries, the styles can be read correctly as if the only operator does not exist; for devices that do not support media queries but support media types (such as IE8), @media screen can be recognized keyword, but since the only operator is read first instead of the screen keyword, this style will be ignored.

Tip: Media queries can also be used in @import rules and tags. For example:

 @import url(example.css) screen and (width:800px);
    //The following code defines that if the page is rendered through the screen and the screen width does not exceed 480px, the shetland.css style sheet is loaded
    <link rel="stylesheet" type="text/css" media="screen and (max-device-width: 480px)" href="shetland.css" />

1.3, Application @media

[Example 1] The and operator is used to match the rules that satisfy the conditions on both sides of the symbol.

 @media screen and (max-width : 600px) {<!-- -->
        /*Match screen devices with a width less than or equal to 600px*/
    }

[Example 2] The not operator is used to negate, that is, everything that does not satisfy the rule is matched.

 @media not print {<!-- -->
        /*Match all devices except printers*/
    }

Note: does not only apply to the entire media query:

 @media not all and (max-width : 500px) {<!-- -->}
    /*Equivalent to*/
    @media not (all and (max-width : 500px)) {<!-- -->}
    /* instead of */
    @media (not all) and (max-width : 500px) {<!-- -->}

In the comma media query list, not will only negate the media query in which it is located, without affecting other media queries.

If you use the not operator in a complex condition, add parentheses explicitly to avoid ambiguity.

[Example 3], (comma) is equivalent to the or operator, used to match if one of the two sides is satisfied:

 @media screen , (min-width : 800px) {<!-- -->
        /*Match screens or devices with a width greater than or equal to 800px*/
    }

[Example 4] In the media type, all is the default value, matching all devices:

 @media all {<!-- -->
        /*Can filter browsers that do not support media*/
    }

Commonly used media types include screen to match the screen display and print to match the printout.

[Example 5] When using media queries, you must add parentheses. One parentheses is a query:

 @media (max-width : 600px) {<!-- -->
        /*Match devices with interface width less than or equal to 600px*/
    }
    @media (min-width : 400px) {<!-- -->
        /*Match devices with interface width greater than or equal to 400px*/
    }
    @media (max-device-width : 800px) {<!-- -->
        /* Match devices (not interfaces) with a width less than or equal to 800px*/
    }
    @media (min-device-width : 600px) {<!-- -->
        /* Match devices (not interfaces) with a width greater than or equal to 600px*/
    }

Tip: When designing mobile web pages, you should use device-width/device-height, because mobile browsers will zoom the page by default. If you match it according to the width and height of the device, it will be closer to the expected effect.

[Example 6] Media queries allow nesting of each other, which can optimize the code and avoid redundancy:

 @media not print {<!-- -->
        /*General style*/
        @media (max-width:600px) {<!-- -->
            /*This bar matches non-printer devices with a width less than or equal to 600px */
        }
        @media (min-width:600px) {<!-- -->
            /*This bar matches non-printer devices with a width greater than or equal to 600px */
        }
    }

[Example 7] When designing a responsive page, users should first determine the adaptive resolution threshold based on actual needs, which is the critical point of page response:

 @media (min-width: 768px){<!-- -->
        /* >=768px device */
    }
    @media (min-width: 992px){<!-- -->
        /* >=992px device */
    }
    @media (min-width: 1200){<!-- -->
        /* >=1200px device */
    }

Note: The following style order is wrong, because the later query range will cover the previous query range, causing the previous media query to be invalid.

 @media (min-width: 1200){<!-- --> }
    @media (min-width: 992px){<!-- --> }
    @media (min-width: 768px){<!-- --> }

Therefore, when we use the min-width media feature, we should design each threshold in order from small to large. In the same way, if max-width is used, each threshold should be designed in order from large to small.

 @media (max-width: 1199){<!-- -->
        /* Devices <=1199px */
    }
    @media (max-width: 991px){<!-- -->
        /* Devices <=991px */
    }
    @media (max-width: 767px){<!-- -->
        /* Devices <=768px */
    }

[Example 8] Users can create multiple style sheets to accommodate the width ranges of different media types. Of course, a more efficient way is to consolidate multiple media queries in a single style sheet file, which can reduce the number of requests:

 @media only screen and (min-device-width : 320px) and (max-device-width : 480px) {<!-- -->
        /*style list */
    }
    @media only screen and (min-width : 321px) {<!-- -->
        /*style list */
    }
    @media only screen and (max-width : 320px) {<!-- -->
        /*style list */
    }

[Example 9] From the perspective of resource organization and maintenance, you can choose to use multiple style sheets to implement media queries, which is more efficient.

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

[Example 10] Use the orientation attribute to determine whether the device screen is currently landscape (the value is landscape) or portrait (the value is portrait).

 @media screen and (orientation: landscape) {<!-- -->
        .iPadLandscape {<!-- -->
            width: 30%;
            float: right;
        }
    }
    @media screen and (orientation: portrait) {<!-- -->
        .iPadPortrait {<!-- -->clear: both;}
    }

However, the orientation attribute is only valid on iPad. For other devices that can rotate the screen (such as iPhone), you can use min-device-width and max-device-width to work around it.

[Extension] Media queries are just a pure CSS method to implement responsive web design. You can also use JavaScript libraries to achieve the same design. For example, download css3-mediaqueries.js (http://code.google.com/p/css3-mediaqueries-js/) and then call it on the page. For old browsers (such as IE6, IE7, IE8), you can consider using css3-mediaqueries.js for compatibility.

 <!–[if lt IE 9]>
    <script src=”http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js”></script>
    <![endif]–>

[Example 11] Demonstrates using jQuery to detect browser width and call different style sheets for different viewports.

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){<!-- -->
        $(window).bind("resize", resizeWindow);
        function resizeWindow(e){<!-- -->
            var newWindowWidth = $(window).width();
            if(newWindowWidth < 600){<!-- -->
                $("link[rel=stylesheet]").attr({<!-- -->href : "mobile.css"});
            }
            else if(newWindowWidth > 600){<!-- -->
                $("link[rel=stylesheet]").attr({<!-- -->href : "style.css"});
            }
        }
    });
    </script>

2. Case practice

2.1. Determine the display screen width

The following example demonstrates how to correctly use the @media rule to determine the range of the current viewport width. The sample code is as follows:

 <style type="text/css">
    .wrapper {<!-- --> /* Define the style of the test strip */
        padding: 5px 10px; margin: 40px;
        text-align:center; color:#999;
        border: solid 1px #999;
    }
    .viewing-area span {<!-- --> /* Hide prompt text information by default */
        color: #666;
        display: none;
    }
    /* Applies to mobile devices, and the maximum width of the device is 480px */
    @media screen and (max-device-width: 480px) {<!-- -->
        .a {<!-- --> background: #ccc;}
    }
    /* Display screen width is less than or equal to 600px */
    @media screen and (max-width: 600px) {<!-- -->
        .b {<!-- -->
            background: red; color:#fff;
            border: solid 1px #000;
        }
        span.lt600 {<!-- --> display: inline-block; }
    }
    /* Display screen width is between 600~900px */
    @media screen and (min-width: 600px) and (max-width: 900px) {<!-- -->
        .c {<!-- -->
            background: red; color:#fff;
            border: solid 1px #000;
        }
        span.bt600-900 {<!-- --> display: inline-block; }
    }
    /* Display screen width is greater than or equal to 900px */
    @media screen and (min-width: 900px) {<!-- -->
        .d {<!-- -->
            background: red; color:#fff;
            border: solid 1px #000;
        }
        span.gt900 {<!-- --> display: inline-block; }
    }
    </style>
    <div class="wrapper a">The maximum device width is 480px. </div>
    <div class="wrapper b">Display screen width less than or equal to 600px </div>
    <div class="wrapper c">The display screen width is between 600~900px</div>
    <div class="wrapper d">Display screen width greater than or equal to 900px </div>
    <p class="viewing-area">
        <strong>Current display screen width:</strong>
        <span class="lt600">Less than or equal to 600px</span>
        <span class="bt600-900">Between 600~900px</span>
        <span class="gt900">Greater than or equal to 900px</span>
    </p>

Example design: When the display screen width is less than or equal to 600px, the

test bar is highlighted, and a prompt message is displayed at the bottom: less than or equal to 600px; when the display screen width is between When it is between 600 and 900px, the

test strip will be highlighted, and a prompt message will be displayed at the bottom: between 600 and 900px; when the display screen width is greater than or equal to 900px, Then highlight the

test strip, and display a prompt message at the bottom: greater than or equal to 900px; when the device width is less than or equal to 480px, highlight < div class="wrapper a">Test strip.

2.2. Design responsive layout

In this case, 3 columns are designed on the page.

  • : Main content column.
  • : Secondary content column.

The constructed page structure is as follows:

 <div id="container">
        <div id="wrapper">
            <div id="main">
                <h1>Shui Tiao Ge Tou·When will the bright moon come</h1>
                <h2>Su Shi</h2>
                <p>…</p>
            </div>
            <div id="sub">
                <h2>Selected Song Ci lyrics</h2>
                <ul>
                    <li>…</li>
                </ul>
            </div>
        </div>
        <div id="sidebar">
            <h2>List of lyricists</h2>
            <ul>
                <li>…</li>
            </ul>
        </div>
    </div>

The design page can adapt to the screen width and present different layouts. When the display screen width is above 999px, display three columns side by side; when the display screen width is above 639px and below 1000px, design two columns to display; when the display screen width is below 640px, display three columns in a stack.

 <style type="text/css">
    /*Default style */
    /* The width of the web page is fixed and displayed in the center */
    #container {<!-- --> width: 960px; margin: auto;}
    /*body width */
    #wrapper {<!-- -->width: 740px; float: left;}
    /*Design 3 columns to display side by side*/
    #main {<!-- -->width: 520px; float: right;}
    #sub {<!-- --> width: 200px; float: left;}
    #sidebar {<!-- --> width: 200px; float: right;}
    /* The window width is above 999px */
    @media screen and (min-width: 1000px) {<!-- -->
        /* 3 columns display */
        #container {<!-- --> width: 1000px; }
        #wrapper {<!-- --> width: 780px; float: left; }
        #main {<!-- -->width: 560px; float: right; }
        #sub {<!-- --> width: 200px; float: left; }
        #sidebar {<!-- --> width: 200px; float: right; }
    }
    /* The window width is above 639px and below 1000px */
    @media screen and (min-width: 640px) and (max-width: 999px) {<!-- -->
        /* 2 columns displayed */
        #container {<!-- --> width: 640px; }
        #wrapper {<!-- --> width: 640px; float: none; }
        .height {<!-- --> line-height: 300px; }
        #main {<!-- --> width: 420px; float: right; }
        #sub {<!-- -->width: 200px; float: left; }
        #sidebar {<!-- -->width: 100%; float: none; }
    }
    /* The window width is below 640px */
    @media screen and (max-width: 639px) {<!-- -->
        /* 1 column display */
        #container {<!-- --> width: 100%; }
        #wrapper {<!-- --> width: 100%; float: none; }
        #main {<!-- -->width: 100%; float: none; }
        #sub {<!-- --> width: 100%; float: none; }
        #sidebar {<!-- --> width: 100%; float: none; }
    }
    </style>

When the display screen width is above 999px, three columns are displayed side by side, and the preview effect is as follows: