Media Queries

Media Queries are a way to serve CSS rules based on the device, or features in the device or browser.

Selecting Media

You may remember the media attribute from the picture element on the Using Images page.

<link rel="stylesheet" type="text/css" href="/styles.css" media="screen" />
A Screen Stylesheet

I can create a completely different stylesheet just for when visitors want to print the page.

<link rel="stylesheet" type="text/css" href="/print.css" media="print" />
A Print Stylesheet

The print stylesheet will only be used when you want to print. The rules for this print stylesheet could include css that will hide the navigation elements in the header and footer, or display the URLs from the links that go to other websites.

@media Rules

@media screen
@media print

Responsive Design

The primary and most ubiquitous use case for media queries is in responsive design. Simply put, responsive design is a design that responds to the device of your visitor.

Recently, an emergent discipline called “responsive architecture” has begun asking how physical spaces can respond to the presence of people passing through them. Through a combination of embedded robotics and tensile materials, architects are experimenting with art installations and wall structures that bend, flex, and expand as crowds approach them. Motion sensors can be paired with climate control systems to adjust a room‘s temperature and ambient lighting as it fills with people. Companies have already produced “smart glass technology” that can automatically become opaque when a room‘s occupants reach a certain density threshold, giving them an additional layer of privacy.

Responsive Web Design by Ethan Marcotte.

Screen resolution is highly fractured, underscoring the importance of using proper responsive techniques.

1920×10808.78%1366×7688.54%360×6407.14%414×8964.25%1536×8643.80%375×6673.53%Other63.96%
Screen Resolutions. Source: Statcounter Worldwide statistics (Aug 2020).

For Mobile First Responsive design, you build the page how it will appear in a mobile device first, and then add rules for how the website will appear in tablet and desktop devices. Admittedly, this takes some guesswork. You can’t simply name it by device, the way you can with print. But you can set it to check for the width of the screen. Mobile devices tend to be less than 640 pixels; Desktop tends to be wider than 1280 pixels; Tablet tends to be between the two.

@media (min-height: 640px) {}
@media (min-height: 1280px) {}

In actuality, you can set as many breakpoints as you want.