CSS: Media Query

By Xah Lee. Date: . Last updated: .

What is Media Query

Media Query applies a set of CSS rules only when a condition is satisfied. Most often used to set CSS depending on user's screen size.

Syntax:

@media all and conditionalExpression { cssRules }

Example, Screen Less Than

If viewport width is less than 600px

@media all and (max-width: 600px) {
 body {background-color: yellow}
}

Once you set the rule, you can drag to change window size to see its effect in realtime.

Example, Screen Greater Than

If viewport width is greater than 1000px

@media all and (min-width: 1000px) {
 body {background-color: cyan}
}

Example, Screen Size Between

If viewport width is between 1000px and 1500px.

@media all and (min-width: 1000px) and (max-width: 1500px) {
 body {background-color: cyan}
}

Real World Example

/* if viewport width is ≥ 1024 px */
@media all and (min-width: 1024px)
{
 body {margin-right: 220px;}
 aside#pVc7y
 {
  display: initial;
  width: 201px;
  }
 }

/* if viewport width is ≤ 1023 px */
@media all and (max-width: 1023px)
{
 body { margin-right: 10px; }

 aside#pVc7y
 {
  display: none;
  width: 10px;
  }
 }

Using Media Query to design site depending on screen size (desktop big display, or cell phone tiny display), is called Responsive Design.

CSS, Media Query

CSS, Advanced