Skip to main content

CSS Media Queries

Responsive web pages depend on media queries, which apply styles according to the characteristics of the device or the environment displaying the page.

To add them to a style sheet, you write the @media rule.


Media Query Syntax

Every media query has one or more media-features, each resolving to true or false, and may also have a media-type. The media-type can be left out unless you use not, which requires one.

The query as a whole is true when the media-type matches the device type and every media-feature is true. Its style rules then take effect, subject to the normal cascading rules.

not: An optional keyword that reverses the meaning of the whole query.

and: The keyword that joins a media-type to one or more media-features.

Media query syntax

The general form of a media query rule, as you would write it.

styles.css
@media [not] media-type and (media-feature: value)
 and (media-feature: value) {
  /* CSS rules to apply */
}

CSS Media Types

A media type names the kind of media the styles target. It is optional, and leaving it out means all.

  • all — Covers every type of media device.
  • print — Applies in print preview mode.
  • screen — Applies to computer screens, tablets and smart-phones.

CSS Media Features

Each media feature tests one particular characteristic of the device. These are among the ones used most often:

  • max-height — The viewport's maximum height.
  • min-height — The viewport's minimum height.
  • height — The viewport's height, scrollbar included.
  • max-width — The viewport's maximum width.
  • min-width — The viewport's minimum width.
  • width — The viewport's width, scrollbar included.
  • orientation — Whether the viewport is landscape or portrait.
  • resolution — The resolution of the screen.
  • prefers-color-scheme — The color scheme (light or dark) the user prefers.

Media Queries Examples

Min-width background color

Once the viewport reaches 480px or more, this media query turns the background color of the body lightgreen.

Prompt
Create a page with a media query that changes the body background color to lightgreen when the viewport width is 480px or wider. Use @media screen and (min-width: 480px).
Output: complete HTML page

Min and max-width background color

Here the background color of the body is lightgreen only while the viewport width stays between 480px and 768px.

Prompt
Create a page with a media query that changes the body background color to lightgreen when the viewport width is between 480px and 768px. Use @media screen and (min-width: 480px) and (max-width: 768px).
Output: complete HTML page