Advanced25 min read

Media Queries Deep Dive

Master CSS media queries for responsive design, including breakpoint strategies, combining conditions, mobile-first vs desktop-first approaches, and specialized media types like print and orientation.

Media Query Syntax

Media queries let you apply CSS rules conditionally based on the characteristics of the device or viewport. The basic syntax is:

css
@media <media-type> and (<condition>) {
  /* CSS rules */
}

Media types include:

  • screen — For screens (the most common).
  • print — For printed pages or print preview.
  • all — Matches all media types (the default if omitted).

The most common conditions test viewport width:

css
/* Applies when viewport is at least 768px wide */
@media (min-width: 768px) {
  .container { max-width: 720px; }
}

/* Applies when viewport is at most 600px wide */
@media (max-width: 600px) {
  .sidebar { display: none; }
}

Mobile-first (recommended): Write base styles for small screens, then use min-width queries to add complexity for larger screens. This approach naturally produces lighter CSS for mobile devices.

Combining Conditions

css
/* AND — both conditions must be true */
@media (min-width: 768px) and (max-width: 1024px) {
  .tablet-only { display: block; }
}

/* OR — use a comma to separate alternatives */
@media (max-width: 600px), (orientation: portrait) {
  .narrow-layout { flex-direction: column; }
}

/* NOT — negates the entire query */
@media not print {
  .screen-only { display: block; }
}

/* Common breakpoint scale */
/* sm:  640px  — large phones      */
/* md:  768px  — tablets            */
/* lg:  1024px — small desktops     */
/* xl:  1280px — large desktops     */
/* 2xl: 1536px — extra large screens */

/* Print styles */
@media print {
  .no-print { display: none; }
  body { color: black; background: white; }
  a { text-decoration: underline; }
}

Modern Media Features

Beyond width, media queries can test many device and user-preference features:

Orientation:

css
@media (orientation: landscape) {
  .hero { height: 50vh; }
}

User preferences:

css
/* Respects OS dark mode setting */
@media (prefers-color-scheme: dark) {
  body { background: #0f172a; color: #e2e8f0; }
}

/* Respects reduced motion setting */
@media (prefers-reduced-motion: reduce) {
  * { animation-duration: 0.01ms !important; }
}

Hover capability:

css
/* Only show hover effects on devices that support hover */
@media (hover: hover) {
  .card:hover { transform: translateY(-4px); }
}

Resolution:

css
/* High-DPI screens (Retina) */
@media (min-resolution: 2dppx) {
  .logo { background-image: url('logo@2x.png'); }
}

These modern features enable you to create experiences that adapt not just to screen size, but to user preferences and device capabilities.

In a mobile-first approach, which type of media query do you primarily use?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.