CSS Media Queries

Learn how to use media queries to create responsive designs that adapt to different screen sizes and device characteristics.

What are Media Queries?

Media queries are a key component of responsive web design. They allow you to apply different CSS styles based on various device characteristics or parameters, such as:

Media queries help create websites that look good and function well on devices of all sizes, from mobile phones to desktop computers.

Basic Media Query Syntax

The basic syntax of a media query includes a media type and one or more expressions that check for specific conditions of that media type:

@media mediatype and (expression) {
  /* CSS rules to apply when the conditions are true */
}

Common media types include:

Example of a media query that applies styles when the screen width is 600px or less:

@media screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

Live Demo: Screen Size Detection

This demo changes color based on your current screen width. Resize your browser window to see it change:

The CSS for this demo uses different media queries to change the background color and text based on screen width:

/* Mobile */
@media (max-width: 576px) {
  .device-demo { background-color: #e74c3c; }
  #screenSize:after { content: "Mobile (max-width: 576px)"; }
}

/* Tablet Small */
@media (min-width: 577px) and (max-width: 768px) {
  .device-demo { background-color: #f39c12; }
  #screenSize:after { content: "Tablet Small (577px - 768px)"; }
}

/* And so on for other screen sizes... */

Common Breakpoints

While you can set breakpoints anywhere, these are commonly used screen width breakpoints:

It's important to note that these breakpoints should be tailored to your specific design needs rather than strictly following these conventions.

Orientation Media Queries

You can apply different styles based on whether the device is in portrait or landscape orientation:

@media (orientation: landscape) {
  /* Styles for landscape orientation */
}

@media (orientation: portrait) {
  /* Styles for portrait orientation */
}

Current orientation demo:

Print Media Queries

You can define styles specifically for printed pages:

@media print {
  /* Styles applied when printing */
  .no-print { display: none; }
  .print-only { display: block; }
}

This paragraph will be hidden when you print this page.

Other Media Features

Beyond screen size and orientation, you can use many other media features in your queries:

Resolution

@media (min-resolution: 192dpi) {
  /* High-resolution screens */
}

Hover Capability

@media (hover: hover) {
  /* Devices that can hover */
}

Preferred Color Scheme

@media (prefers-color-scheme: dark) {
  /* User prefers dark mode */
}

Pointer Precision

@media (pointer: coarse) {
  /* Touch input devices */
}

Best Practices