Sub topic 3
Anatomy of a Media Query
This chapter assumes you can read CSS selectors and rules, know how the cascade resolves conflicts, and are comfortable with px, em, and rem. It takes apart a single media query so you can see what each piece does and why a malformed query fails without any warning. Later chapters cover width features in detail and how to combine conditions.
What a media query is
A media query is a condition that the browser evaluates against the current environment: the viewport, the output device, or the user's settings. If the condition is true, the CSS guarded by the query applies. If it is false, the browser skips that CSS.
The most common form is the @media at-rule:
.sidebar {
display: none;
}
@media (min-width: 48em) {
.sidebar {
display: block;
}
}The .sidebar is hidden by default. When the viewport is at least 48em wide, the nested rule applies and shows it.
The parts of a query
An @media rule has a prelude and a block. The prelude is the query. The block holds ordinary CSS rules.
@media screen and (min-width: 40em) {
.nav { display: flex; }
}| Part | Example | Role |
|---|---|---|
| At-rule keyword | `@media` | Starts a conditional group rule |
| Media type | `screen` | Broad category of output device |
| Operator | `and` | Joins a type and a condition |
| Media feature | `(min-width: 40em)` | A specific test, always in parentheses |
| Block | `{ ... }` | The rules that apply when the query is true |
Media types
A media type names a broad category of device. Three types are current:
allmatches every device. It is the default when you omit the type.screenmatches devices that show the page on a screen.printmatches print output and print preview.
Older types such as tv, projection, handheld, tty, aural, and speech are deprecated. Browsers still parse them but they never match. A query like @media handheld { ... } therefore does nothing, and no error appears.
Because the type is optional, these two queries are equivalent:
@media (min-width: 40em) { .a { color: green; } }
@media all and (min-width: 40em) { .a { color: green; } }You only need to write a type when you want to restrict a rule, for example to screen. Print styles get their own chapter later.
Media features
A media feature tests one property of the environment. It always sits inside parentheses. There are two common shapes:
- A feature with a value, such as
(min-width: 40em)or(orientation: landscape). - A feature on its own, such as
(color)or(hover). This is the boolean context: the query is true if the feature has any value other than zero ornone.
Some features accept min- and max- prefixes, such as width, height, and resolution. Others take only fixed keywords, such as orientation (portrait or landscape) and hover (none or hover). Prefixes on keyword features are invalid.
@media (orientation: landscape) {
.gallery { grid-template-columns: repeat(4, 1fr); }
}
@media (color) {
.badge { color: crimson; }
}Width-related features are the main topic of the next chapter.
Joining a type and a feature
Use and to require both a type and one or more features:
@media screen and (min-width: 40em) and (orientation: landscape) {
.hero { min-height: 60vh; }
}Two syntax details are easy to miss:
- When a media type is present, it comes first.
(min-width: 40em) and screenis invalid. andneeds whitespace on both sides.and(min-width: 40em)is invalid.
The not, only, and comma operators are covered in the chapter on combining conditions.
Where media queries can live
The @media rule is the most flexible form, but it is not the only one.
In a link element
The media attribute on <link> limits when a stylesheet applies:
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="print.css" media="print">
<link rel="stylesheet" href="wide.css" media="(min-width: 64em)">Note that the attribute holds the query without the @media keyword. Browsers generally still download a non-matching stylesheet, at a lower priority, so that it is ready if the condition becomes true.
With @import
@import accepts a query after the URL. It must appear before other rules in the stylesheet:
@import url("print.css") print;
@import url("wide.css") (min-width: 64em);@import delays loading because the browser discovers the imported file only after fetching the importing stylesheet. Prefer <link> elements for performance.
Nested inside other rules
Modern CSS allows @media inside a style rule. The nested block is scoped to the parent selector:
.card {
padding: 0.5rem;
@media (min-width: 40em) {
padding: 1.5rem;
}
}This is equivalent to writing a separate @media block containing .card { padding: 1.5rem; }. Check your target browsers before relying on nesting. You can also place @media inside other conditional rules, such as @supports, and nest queries inside each other.
Behavior to keep in mind
Queries are re-evaluated live
The browser checks the condition continuously. Resizing the window, rotating a phone, or changing a system setting can flip a query from false to true, and the page restyles immediately. You do not need JavaScript for this.
Queries add no specificity
A rule inside @media has the same specificity as the same rule outside it. Source order still decides ties. This is a frequent source of confusion:
@media (min-width: 40em) {
.title { font-size: 2rem; }
}
.title {
font-size: 1rem;
}Here the later .title rule always wins, so the larger size never applies. Put the base rule first and the query after it.
em and rem do not follow your CSS
Inside a media query, em and rem both resolve against the browser's initial font size, usually 16px. They ignore any font-size you set on html or body. That is why 40em means 640px in a query even if your page sets html { font-size: 62.5%; }. Because the units follow the user's browser font setting, queries written in em also respond when users enlarge their default text.
Invalid queries fail silently
If a query cannot be parsed, the browser treats it as not all, which never matches. The block is ignored and nothing appears in the console. Common causes:
- Missing parentheses:
@media min-width: 40em. - Missing unit on a nonzero length:
(min-width: 640). - Misspelled feature:
(min-widht: 40em). - Missing space around
and. - A prefix on a keyword feature:
(min-orientation: landscape).
Exercises
Exercise
This rule is meant to apply on screens at least 50em wide, but it never applies. Find all the errors: @media (min-width: 50) and screen { .menu { display: flex; } }
Show answer
There are two errors. The length 50 has no unit, so the feature is invalid. The media type screen must come before the feature, not after it. A corrected version is @media screen and (min-width: 50em) { .menu { display: flex; } }. Because the query is invalid, the browser treats it as not all and ignores the block without reporting an error.
Exercise
Your stylesheet contains html { font-size: 62.5%; } and the query @media (min-width: 40em). At what viewport width in pixels does the query start matching, assuming the user has not changed the browser's default font size?
Show answer
640px. In media queries, em resolves against the browser's initial font size (16px by default), not against your html font-size rule, so 40em equals 40 × 16 = 640px.