What Are CSS Media Queries?
CSS media queries are conditional CSS rules that apply styles based on device characteristics. They form the cornerstone of responsive design, enabling a single codebase to serve multiple device types effectively.
Modern web development with frameworks like Next.js demands mastery of media queries to deliver exceptional user experiences while maintaining optimal Core Web Vitals scores. This comprehensive guide covers everything from basic syntax to advanced optimization techniques. Media queries work seamlessly with CSS frameworks and CSS reset techniques to create robust responsive systems.
Key Topics Covered:
Understanding CSS Media Query Fundamentals
The Basic Syntax Structure
The @media at-rule initiates a media query block, containing expressions that evaluate to true or false. When conditions are met, styles within the block are applied. Understanding this syntax structure is fundamental to writing effective responsive stylesheets.
Media queries consist of a media type (optional, defaults to "all") and one or more media features that describe specific device characteristics. Each media feature can be prefixed with min- or max- to create range queries. According to MDN Web Docs, media queries allow applying CSS styles depending on device characteristics like screen resolution, orientation, viewport width, and user preferences.
Code Example: Basic Media Query Syntax
/* Mobile-first base styles apply to all devices */
.card {
padding: 1rem;
font-size: 1rem;
}
/* Apply when viewport is at least 768px wide */
@media (min-width: 768px) {
.card {
padding: 1.5rem;
font-size: 1.125rem;
}
}
/* Apply when viewport is between 768px and 1199px */
@media (min-width: 768px) and (max-width: 1199px) {
.card {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
}
/* Apply when device is in landscape orientation */
@media (orientation: landscape) {
.card {
flex-direction: row;
}
}
Media Types and Their Applications
Media types define the general category of device. While most modern web development focuses on screen, understanding all types helps optimize for specific use cases. The four active media types are:
- screen: The primary type for web browsers on monitors, tablets, phones, and other devices with displays
- print: Optimizes content for printed pages and PDF generation, hiding interactive elements
- all: The default type that matches all devices (often omitted)
- speech: Designed for screen readers and speech synthesis devices
/* Print-specific styles */
@media print {
nav, footer, .no-print {
display: none;
}
body {
font-size: 12pt;
line-height: 1.5;
}
a[href]::after {
content: " (" attr(href) ")";
font-size: 0.8em;
}
}
/* Speech synthesis styles */
@media speech {
h1 {
pause: 0.5s;
}
}
Common Use Cases
- Mobile layout adjustments for smaller viewports
- Tablet-specific optimizations for mid-range screens
- Desktop enhancements for wider displays
- Print-friendly styles that remove navigation and optimize readability
- Dark mode themes respecting system preferences
- Reduced motion animations for accessibility
Modern media queries can detect device capabilities beyond screen size
Viewport-Based Features
Adapt layouts based on screen dimensions using width, height, and orientation features with min- and max- prefixes.
Device Capability Detection
Detect input methods with hover and pointer features to optimize experiences for touch, mouse, and hybrid devices.
User Preference Features
Respect system settings with prefers-color-scheme, prefers-reduced-motion, and other accessibility-focused features.
Resolution Features
Target high-DPI displays and optimize image assets using resolution and min-resolution media features.
Viewport-Based Features in Depth
Viewport-based features are the most commonly used in responsive design. They enable fluid layouts that adapt to device dimensions seamlessly, forming the backbone of modern responsive web development practices. Understanding how media queries interact with the CSS box model is essential for creating layouts that reflow correctly across breakpoints.
Common Breakpoint Ranges
Understanding typical device dimensions helps establish a baseline for responsive implementations. While best practice is to define breakpoints based on content rather than specific devices, these ranges provide useful starting points:
- Mobile: 320px to 767px (smartphones in portrait)
- Tablet: 768px to 1023px (tablets and large phones in landscape)
- Laptop: 1024px to 1439px (small desktops and landscape tablets)
- Desktop: 1440px and above (standard monitors)
As noted by BrowserStack, deploying CSS media queries and breakpoints that fit the device preferences of the target audience is essential for responsive design success.
Code Examples: Responsive Breakpoints
/* Mobile-first base styles */
.container {
padding: 1rem;
}
@media (min-width: 640px) {
.container {
padding: 1.25rem;
}
}
/* Tablet */
@media (min-width: 768px) {
.container {
padding: 1.5rem;
}
}
/* Laptop */
@media (min-width: 1024px) {
.container {
max-width: 1024px;
margin: 0 auto;
padding: 2rem;
}
}
/* Desktop */
@media (min-width: 1280px) {
.container {
max-width: 1280px;
padding: 2.5rem;
}
}
/* Large desktop */
@media (min-width: 1536px) {
.container {
max-width: 1440px;
}
}
Fluid typography scales smoothly between breakpoints using viewport units:
/* Fluid typography that scales between viewports */
h1 {
font-size: clamp(2rem, 5vw, 4rem);
}
p {
font-size: clamp(1rem, 2.5vw, 1.25rem);
}
Device Orientation Adaptations
Modern layouts often require different approaches for portrait and landscape orientations, particularly for media-heavy content and gaming interfaces:
/* Image gallery: different grid in each orientation */
.gallery {
display: grid;
grid-template-columns: 1fr;
gap: 0.5rem;
}
@media (orientation: landscape) {
.gallery {
grid-template-columns: repeat(3, 1fr);
}
}
/* Video player: adjust aspect ratio */
.video-container {
aspect-ratio: 9/16;
}
@media (orientation: landscape) {
.video-container {
aspect-ratio: 16/9;
max-width: 80vw;
}
}
User Preference Features
User preference features allow websites to respect system settings, creating inclusive experiences for all users:
/* Dark mode support */
@media (prefers-color-scheme: dark) {
body {
background-color: #1a1a1a;
color: #f0f0f0;
}
a {
color: #64b5f6;
}
}
/* Reduced motion for accessibility */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* High contrast mode */
@media (prefers-contrast: more) {
body {
--text-primary: #000000;
--text-secondary: #1a1a1a;
--border-color: #000000;
}
}
Creating Complex and Effective Media Queries
Logical Operators and Combining Conditions
Complex responsive designs require combining multiple conditions. Understanding logical operators enables precise control over style application, reducing code duplication and improving maintainability across your responsive stylesheets.
Combining Conditions
/* AND - Both conditions must be true */
@media (min-width: 768px) and (max-width: 1024px) {
.sidebar {
width: 280px;
position: fixed;
}
}
/* OR - At least one condition must be true */
@media (min-width: 768px), (orientation: landscape) {
.hero {
min-height: 60vh;
}
}
/* NOT - Negates the entire media query */
@media not screen and (min-width: 1200px) {
.full-bleed {
margin: 0 -1rem;
}
}
/* ONLY - Prevents older browsers from applying styles */
@media only screen and (min-width: 1024px) {
.desktop-nav {
display: flex;
}
}
When using the NOT operator, it negates the entire media query, so you must include the media type. The comma operator acts as OR, applying styles when any condition matches. Parentheses group conditions to create complex boolean logic.
Mobile-First vs. Desktop-First Approaches
The choice between mobile-first and desktop-first breakpoint strategies significantly impacts code organization and performance. Mobile-first has become the industry standard for modern web applications:
Mobile-First (Recommended) - Write base styles for mobile, add complexity with min-width queries:
/* Base styles - mobile */
.layout {
display: block;
}
/* Tablet and up */
@media (min-width: 768px) {
.layout {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
/* Desktop and up */
@media (min-width: 1024px) {
.layout {
grid-template-columns: 1fr 3fr;
gap: 2rem;
}
}
Desktop-First - Write base styles for desktop, scale down with max-width queries:
/* Base styles - desktop */
.layout {
display: grid;
grid-template-columns: 1fr 3fr;
}
/* Tablet and down */
@media (max-width: 1023px) {
.layout {
grid-template-columns: 1fr 2fr;
}
}
/* Mobile and down */
@media (max-width: 767px) {
.layout {
display: block;
}
}
Mobile-first typically results in better performance because mobile styles are loaded first and additional styles are progressively enhanced for larger screens. This approach also aligns naturally with how modern frameworks like Next.js handle responsive styling through CSS modules and utility classes. Combined with CSS animatable properties, you can create smooth transitions between breakpoints without performance penalties.
When to Define Custom Breakpoints
While common breakpoints exist based on device dimensions, the best practice is defining breakpoints based on content rather than specific devices. Identify where your design naturally needs to adapt:
- Where text lines become too long for comfortable reading (~65-75 characters ideal)
- Where images or cards need to change layout to remain visually balanced
- Where navigation requires restructuring for touch interaction
- Where data tables need special handling for horizontal space
Consider creating a design system token layer for consistent breakpoint management:
/* Design system breakpoint tokens */
:root {
--bp-sm: 640px;
--bp-md: 768px;
--bp-lg: 1024px;
--bp-xl: 1280px;
--bp-2xl: 1536px;
}
@media (min-width: var(--bp-md)) {
/* Tablet styles */
}
Performance Optimization for Media Queries
Critical Rendering Path Considerations
How media queries are implemented affects how quickly pages render. Understanding the critical rendering path helps optimize responsive stylesheets. According to MDN's CSS performance guide, media queries are important for responsive web design and help optimize the critical rendering path. The browser blocks rendering until certain resources are loaded, making efficient media query usage critical for performance.
When the browser parses CSS, it evaluates media queries to determine which styles apply to the current viewport. Styles in matching media queries become part of the render tree, directly impacting First Contentful Paint (FCP) and Largest Contentful Paint (LCP).
Optimize the critical path by:
- Inlining critical responsive styles directly in the HTML head
- Loading non-critical responsive styles asynchronously with
media="all"on link elements - Using the
content-visibilityproperty to skip rendering off-screen content
Avoiding Common Performance Pitfalls
Many responsive implementations include performance issues that accumulate over time:
Problem: Overlapping media queries
/* Before: Redundant and overlapping */
@media (min-width: 600px) {
.card { padding: 1rem; }
}
@media (min-width: 700px) {
.card { padding: 1.25rem; }
}
@media (min-width: 800px) {
.card { padding: 1.5rem; }
}
/* After: Consolidated with cascade */
@media (min-width: 600px) {
.card {
padding: 1rem;
}
}
@media (min-width: 800px) {
.card {
padding: 1.5rem;
}
}
Problem: Excessive specificity
/* Before: Overly specific selectors */
@media (min-width: 768px) {
body.home main .content-section .card-wrapper .card {
display: grid;
}
}
/* After: Cleaner selectors */
@media (min-width: 768px) {
.card {
display: grid;
}
}
Problem: Layout-triggering animations
/* Before: Triggers reflow on every frame */
@media (prefers-reduced-motion: no-preference) {
.animate-width {
width: 100px;
animation: grow 1s ease;
}
@keyframes grow {
to { width: 200px; }
}
}
/* After: Use transform instead */
@media (prefers-reduced-motion: no-preference) {
.animate-scale {
transform: scale(1);
animation: expand 1s ease;
}
@keyframes expand {
to { transform: scale(1.2); }
}
}
Optimizing CSS Bundle Size
Efficient media query organization keeps responsive styles lean as projects grow:
- Group media queries at the end of stylesheets or in separate files loaded conditionally
- Use CSS custom properties for breakpoint-agnostic values that cascade naturally
- Leverage modern layout techniques like flexbox and grid that reduce media query dependency
- Use build tools to analyze and report media query counts
- Remove unused responsive styles during tree shaking
Performance Checklist
- Use min-width for mobile-first approach (reduces overall CSS for mobile)
- Inline critical responsive styles in the document head
- Avoid redundant or overlapping queries that multiply match attempts
- Minimize layout-triggering animations within media query blocks
- Test with Lighthouse performance audits regularly
- Monitor Core Web Vitals across different viewport sizes
- Use the
will-changeproperty sparingly for predictable rendering
Modern CSS Features Enhancing Media Queries
Container Queries: Component-Based Responsiveness
Container queries represent the next evolution in responsive styling, allowing components to adapt to their parent container rather than the viewport. This capability is transformative for component-based architectures common in Next.js applications.
/* Define a container with query context */
.card-grid {
container-type: inline-size;
container-name: card-container;
}
/* Container query for responsive components */
@container card-container (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 1.5rem;
}
}
@container card-container (min-width: 600px) {
.card {
grid-template-columns: repeat(2, 1fr);
}
}
Container queries differ fundamentally from media queries: media queries adapt styles based on viewport dimensions, while container queries adapt based on parent container dimensions. This means the same card component can display differently when placed in a sidebar versus a main content area. Browser support has expanded significantly, with all major browsers now supporting container queries, though progressive enhancement remains a best practice.
CSS Custom Media Queries
CSS custom media queries (Level 4 specification) allow defining named breakpoints for reuse throughout stylesheets, improving maintainability and consistency in large design systems:
/* Define custom media query names in a design tokens file */
@custom-media --mobile (width < 48rem);
@custom-media --tablet (48rem <= width < 80rem);
@custom-media --desktop (width >= 80rem);
@custom-media --touch (hover: none) and (pointer: coarse);
@custom-media --high-contrast (prefers-contrast: more);
/* Use custom media queries throughout stylesheets */
@media (--mobile) {
.navigation {
flex-direction: column;
}
}
@media (--tablet) {
.navigation {
justify-content: space-around;
}
}
@media (--desktop) {
.navigation {
gap: 2rem;
}
}
While browser support for @custom-media is currently limited (supported in Chrome 120+, Firefox 113+, and behind flags in Safari), PostCSS plugins like postcss-custom-media enable usage today with automatic compilation to standard media queries.
Emerging Features
The CSS specification continues to evolve with new media query capabilities on the horizon:
- scripting: Detect whether JavaScript is enabled (Level 5)
- video-prefix and video: Detect video capabilities and display state
- environment-blending: Adapt for different reality types (mixed reality)
- dynamic-range: Detect HDR display capabilities
Stay current with CSS specifications through web.dev's media queries guide and the official W3C CSS specifications.
When to Use Container Queries vs Media Queries
Choose container queries when building reusable components that must adapt to their container context. Choose media queries for overall page layout and viewport-dependent design decisions.
| Use Case | Recommended Approach | Reason |
|---|---|---|
| Page layout (header, sidebar, main) | Media queries | Layout depends on viewport |
| Reusable card components | Container queries | Cards adapt to their container |
| Navigation menus | Hybrid approach | Menu structure (media) + item sizing (container) |
| Image galleries | Container queries | Gallery adapts to grid column width |
| Typography scaling | Viewport units + media queries | Text needs viewport context |
For best results, combine both approaches: use media queries for the overall page structure and container queries for component-level adaptations within that structure.
Code Organization
Co-locate responsive styles with components, use consistent naming conventions, and maintain clear documentation for breakpoint strategies.
Testing Strategy
Test across real devices, use browser DevTools responsive mode, and implement automated visual regression testing for responsive layouts.
Accessibility First
Ensure touch target sizing (44x44px minimum), text reflow, focus management, and respect user preference media features like reduced motion.
Performance Monitoring
Regularly audit with Lighthouse, monitor Core Web Vitals across viewports, and track responsive performance over time.
Frequently Asked Questions
What are the standard breakpoints for responsive design in 2025?
While common breakpoints exist (mobile: 0-767px, tablet: 768-1023px, desktop: 1024px+), best practice is to define breakpoints based on your content rather than specific devices. Modern frameworks like Tailwind CSS use breakpoints like sm: 640px, md: 768px, lg: 1024px, xl: 1280px, 2xl: 1536px.
Should I use mobile-first or desktop-first media queries?
Mobile-first (using min-width) is the recommended approach for most projects. It typically results in better performance because mobile styles are loaded first and additional styles are progressively enhanced for larger screens. This approach aligns with how modern frameworks like Next.js handle responsive styling.
How do container queries differ from media queries?
Media queries adapt styles based on viewport dimensions, while container queries adapt based on parent container dimensions. Container queries are ideal for reusable components that need to respond to their container regardless of where they're placed. Media queries remain essential for overall page layout adaptations.
What performance impact do media queries have?
Media queries affect the critical rendering path. Overly complex or numerous media queries can slow page load. Best practices include: using mobile-first approach, inlining critical responsive styles, avoiding redundant queries, and minimizing layout-triggering animations within media query blocks.
How do I test responsive designs effectively?
Use browser DevTools responsive design mode for initial testing, but supplement with real device testing for accurate touch interaction and performance validation. Automated visual regression testing tools like Percy or Chromatic help catch responsive regressions. Always test Core Web Vitals across different viewport sizes.
What are the key user preference media features?
The most important user preference features are prefers-color-scheme (light/dark mode), prefers-reduced-motion (accessibility), prefers-contrast (visual clarity), and scripting (JavaScript availability). Respecting these preferences creates inclusive experiences for all users.
Sources
- MDN Web Docs - Using media queries - The authoritative source for CSS documentation covering media query syntax, types, and features
- BrowserStack - A Complete Guide to CSS Media Query - Comprehensive developer guide covering breakpoints and responsive design patterns
- MDN - CSS performance optimization - Performance guidance for CSS including media query optimization
- web.dev - Media queries - Google's official web development guide covering responsive design best practices