Responsive web design

An important principle of software development is <i>don't repeat yourself</i>, that means that the code that can be shared should be shared (this is not true for all instances, but that's a discussion for another time). In our age of laptops, tablets, phones and phablets, our webpages should behave different on each device in order to create an optimal user experience. E.g. should you use a desktop layout on your phone, the font size could be too small or large to give an optimal reading experience. Previously this was fixed using different stylesheets or different versions of the webpage for smaller screens. This obviously defy the DRY principle. With CSS3 we got a feature called media queries. With media queries, we can introduce breakpoints in our design, and share the code that are used in both mobile and desktop design.

Why not just use percentage when defining sizes? Well, using percentage instead of

You write a media query as such, in your CSS document:

p{
    font-size: 22px;
}

@media (max-width: 600px){
    p{
        font-size: 14px;
    }
}

The media query starts with @media, followed by an expression that resolves to either true or false. There can be zero or more expressions in the media query. For the media query to be applied, all expressions must resolve to true. When the media query is applied, it follows the rules for normal cascading. In the example above the expression is max-width: 600px, meaning that the style within this media query will be applied when the browser window width is max 600px (600px and less).

Media queries are case insensitive. Media queries involving unknown media types are always false.

max-width is not the only expression there is. Below you will find an overview over the most important expressions. These are divided into media types and media features. The max-width seen in the example is a media feature.

Last updated