Query Selectors in CSS

Posted on January, 07 2014

CSS3 has some funky features that allow you to make dynamic websites without using JavaScript once. One of these features is the @media selector. documentation

@media allows you to enable properties on elements depending on screen size.

To do this, simply type @media { css }

example:

@media (min-height:600px) and (orientation:landscape) {
    div {
        background-color:red;
    }
}

(min-height:600px) is a condition where min-height checks if the minimum height is 600px. The and is a logical operator specifying that both conditions on either side must evaluate to true, to be true.

You can implement this selector when loading style-sheets onto your HTML document to select between completely different style-sheets based on screen size.

<link rel="stylesheet" media="only screen and (max-width: 999px) and (min-width:635px)" href="style.css" />

The media attribute in the link element allows a stylesheet to be evaluated & conditionally loaded.

Here's an example of loading 3 different stylesheets for desktop, tablet and mobile

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" media="only screen and (max-width: 634px)" href="mobile.css" />
<link rel="stylesheet" media="only screen and (max-width: 999px) and (min-width:635px)" href="tablet.css" />
<link rel="stylesheet" media="only screen and (min-width: 1000px)" href="desktop.css" />

Here's a list of all the conditions (documentation):

  • width | min-width | max-width

  • width | min-width | max-width

  • device-width | min-device-width | max-device-width

  • device-height | min-device-height | max-device-height

  • aspect-ratio | min-aspect-ratio | max-aspect-ratio

  • device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio

  • color | min-color | max-color

  • color-index | min-color-index | max-color-index

  • monochrome | min-monochrome | max-monochrome

  • resolution | min-resolution | max-resolution

  • scan | grid