What are media queries and why are they used?

HighIntermediateCss
Quick Answer

Use media queries as a production breakpoint strategy: adapt layouts, respect user preferences, and avoid responsive pitfalls caused by viewport-only thinking.

Answer

Overview

Media queries are not just responsive CSS trivia. In production they define your breakpoint strategy, user-preference handling, and fallback rules when layouts change across devices. Strong answers talk about mobile-first defaults, pitfalls like overfitting to a few screen widths, and when viewport queries should give way to container queries.

Feature

Example

Purpose

min-width

@media (min-width: 768px)

Applies when the viewport is at least 768px wide.

max-width

@media (max-width: 600px)

Applies when the viewport is 600px wide or less.

orientation

@media (orientation: landscape)

Applies styles for landscape or portrait mode.

resolution

@media (min-resolution: 300dpi)

Targets high-resolution (Retina) displays.

Common media query conditions

Example: Responsive Layout

CSS
body {
  font-size: 16px;
}
@media (max-width: 768px) {
  body {
    font-size: 14px;
  }
}
@media (max-width: 480px) {
  body {
    font-size: 12px;
  }
}
                  

This example adjusts the text size for tablets and mobile screens, improving readability on smaller devices.

Combining Conditions
Media queries can combine multiple conditions using logical operators:

  • and – combine features (@media (min-width: 600px) and (orientation: landscape)).
  • not – exclude specific conditions.
  • only – prevent older browsers from applying the rule.

Mobile-First Approach
Modern best practice is to start with default (mobile) styles and add media queries for larger viewports. This ensures faster rendering and fewer overrides:

@media (min-width: 768px) { /* tablet styles */ }
@media (min-width: 1024px) { /* desktop styles */ }

Advanced Features

  • Media queries support prefers-color-scheme for dark/light mode.
  • prefers-reduced-motion helps accessibility by disabling animations for users who prefer reduced motion.
  • Container queries (in modern browsers) extend this concept to parent element widths rather than the viewport.

Still so complicated?

Think of media queries as smart CSS switches — they turn on or off specific styles depending on the screen’s size or features, just like adaptive headlights adjusting to road conditions.

Summary
  • Media queries adapt designs to different screen sizes and device capabilities.
  • Essential for responsive design and accessibility.
  • Support conditions like width, orientation, resolution, and user preferences.
  • Combine with a mobile-first strategy for performance and scalability.
Similar questions
Guides
Preparing for interviews?

Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.