Media Queries

The display of responsive pages will change depending on the device or window on which they are to be viewed.

Common uses for responsive pages is for:

  • printing on paper/PDF
    (hiding unnecessary page elements, using black on white text)
  • screens with narrower displays (tablets/smartphones)
    (replacing a horizonal navigation bar with a vertical, or hamburger menu)

Within the CSS, default values are written first, with media queries defined underneath. When coding media queries, only the changes are styled.

@media not|only mediatype and (expressions) {
    CSS Code;
}

Three media types are in the Advanced Higher course: all, screen and print (there is also a “speech” type for screenreaders that read out the page contents).

Only the max-width media feature is required (other features include min-width and orientation).

Note: only the media query declaration itself is included in the Advanced Higher course.

Examples

Navigation Bars

A horizontal navigation bar uses the float and width properties to display li elements alongside each other, suitable for a wide screen display.

For screen displays under 600 pixels wide, the height of the nav container is increased, and each navigation li is increased to the full width of the display so they appear underneath each other:

@media screen and (maxwidth:600px) {
    nav {
        height: 125px;
    }
    nav ul li {
        width:100%;
        height:20px;
        font-size:8pt}
    }

Printing

Light coloured text on a dark background may work well on a display, but not so well on paper.

Items suitable for displaying on screen may not be needed for printing – eg when printing a receipt.

@media print { 
    * { 
        color: black;
        background-colour: white; 
    }

    .screenonly {
        display: none;
    }
[/css]