What Are CSS Media Queries?
CSS Media Queries are a core feature of modern web development that allow you to apply CSS rules conditionally, based on characteristics of the user's device or browser viewport. Introduced as part of the CSS3 specification, media queries give developers the power to create responsive designs that adapt seamlessly across different screen sizes, resolutions, and device capabilities.
At their simplest, a media query is a logical expression that evaluates to either true or false. When the condition evaluates to true, the enclosed CSS rules are applied. When false, those rules are ignored entirely. This conditional logic is what enables a single stylesheet to serve multiple layouts without relying on JavaScript or server-side detection.
/* Basic structure of a media query */
@media (max-width: 768px) {
.container {
width: 100%;
padding: 10px;
}
}
In the example above, the .container element will only receive the width: 100% and padding: 10px rules when the viewport width is 768 pixels or narrower. On wider screens, those rules are simply not applied.
Why Media Queries Matter
🚀 Deploy your AI agent in 10 minutes
Managed Hermes hosting. Zero DevOps. 100M tokens/mo included.
Try it free →Media queries are the backbone of responsive web design. Without them, websites would either appear exactly the same on every device — forcing mobile users to pinch and zoom to read tiny text — or would require entirely separate mobile and desktop codebases. Media queries bridge that gap elegantly.
Here are the key reasons media queries are indispensable:
- Device Diversity: The modern web is accessed from phones, tablets, laptops, desktop monitors, and even smart TVs. Each has different viewport dimensions, pixel densities, and interaction modes. Media queries let you tailor the experience to each.
- User Experience: A layout optimized for a 27-inch monitor with a mouse is unusable on a 6-inch touchscreen. Media queries allow you to restructure navigation, adjust font sizes, and reposition content to match the user's context.
- Performance: You can use media queries to load only the appropriate assets. For example, hide heavy background images on mobile devices to save bandwidth and improve load times.
- Accessibility: Features like
prefers-reduced-motionandprefers-color-schemeallow your site to respect user preferences for motion reduction and dark/light modes. - Future-Proofing: As new device categories emerge, media queries provide a flexible mechanism to adapt without rewriting your entire CSS architecture.
How to Use Media Queries
Basic Syntax
A media query consists of an optional media type (such as screen or print) and one or more media feature expressions that test for specific conditions. The general syntax follows this pattern:
@media [media-type] and (media-feature) {
/* CSS rules go here */
}
You can also use the only keyword to hide rules from older browsers that might misinterpret the query, or the not keyword to negate a condition:
/* Apply styles only to screen devices with a max-width of 600px */
@media only screen and (max-width: 600px) {
body {
font-size: 14px;
}
}
/* Negation: apply to everything EXCEPT print media */
@media not print {
.header {
background-color: #333;
}
}
Common Media Types
The media type specifies the broad category of device you're targeting. The most commonly used types are:
all— Applies to all devices (this is the default if no type is specified)screen— Targets devices with a screen, such as phones, tablets, and desktop monitorsprint— Applies styles when the document is being printed or viewed in print previewspeech— Intended for screen readers and speech synthesizers
/* Print-specific styles: remove backgrounds, adjust typography */
@media print {
body {
background: none;
color: #000;
font-size: 12pt;
}
.no-print {
display: none;
}
}
Width-Based Queries: The Heart of Responsive Design
Width-based media queries are by far the most frequently used. They allow you to define breakpoints where your layout shifts to accommodate different viewport sizes. The two primary width features are:
min-width— Triggers when the viewport is at least the specified widthmax-width— Triggers when the viewport is at most the specified width
A common strategy is to use a mobile-first approach, where you write base styles for the smallest screens and then layer on complexity with min-width queries for progressively larger breakpoints:
/* Mobile-first base styles (no query needed — applies everywhere) */
.card-grid {
display: flex;
flex-direction: column;
gap: 16px;
}
/* Tablet breakpoint: 768px and wider */
@media (min-width: 768px) {
.card-grid {
flex-direction: row;
flex-wrap: wrap;
}
.card {
flex: 1 1 calc(50% - 16px);
}
}
/* Desktop breakpoint: 1024px and wider */
@media (min-width: 1024px) {
.card-grid {
flex-wrap: nowrap;
}
.card {
flex: 1 1 calc(25% - 16px);
}
}
Alternatively, you can use a desktop-first approach with max-width queries, overriding the complex desktop layout with simpler mobile rules at narrower breakpoints. Both approaches are valid — choose the one that aligns with your design process and target audience.
Height-Based Queries
While width gets most of the attention, height-based media queries can be extremely useful for full-screen layouts, hero sections, and modal dialogs:
/* Adjust hero section when viewport height is limited */
@media (max-height: 600px) {
.hero {
min-height: 300px;
padding-top: 20px;
}
.hero__title {
font-size: 1.5rem;
}
}
Orientation Queries
Detecting whether a device is in portrait or landscape mode is straightforward with the orientation media feature:
/* Portrait mode: typically narrow and tall */
@media (orientation: portrait) {
.sidebar {
display: none;
}
.main-content {
width: 100%;
}
}
/* Landscape mode: wide and short */
@media (orientation: landscape) {
.sidebar {
display: block;
width: 250px;
}
}
Resolution and Pixel Density Queries
For high-DPI (retina) displays, you can target devices based on their pixel ratio. This is invaluable for serving higher-resolution images or adjusting icon sizes:
/* Target devices with a pixel ratio of 2 or higher */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.logo {
background-image: url('logo@2x.png');
background-size: contain;
}
}
/* Modern syntax using min-resolution */
@media (min-resolution: 2dppx) {
.icon {
/* Use SVG or larger raster assets */
}
}
User Preference Queries (Level 4 and 5)
Modern CSS Media Queries go far beyond screen dimensions. The Level 4 and Level 5 specifications introduce media features that respond to user preferences and device capabilities, enabling more inclusive and personalized experiences:
/* Dark mode support */
@media (prefers-color-scheme: dark) {
body {
background-color: #1a1a1a;
color: #e0e0e0;
}
a {
color: #8ab4f8;
}
}
/* Respect reduced motion preferences */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
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: high) {
body {
background: white;
color: black;
}
button {
border: 2px solid black;
}
}
/* Inverted colors preference */
@media (inverted-colors: inverted) {
img, video {
filter: invert(1);
}
}
Combining Multiple Conditions
Real-world responsive design often requires chaining multiple conditions together. You can combine media features using the and operator, or create alternative branches using commas (which function as a logical OR):
/* Both conditions must be true */
@media screen and (min-width: 768px) and (orientation: landscape) {
.gallery {
columns: 3;
}
}
/* Either condition triggers the styles (OR logic via commas) */
@media (max-width: 480px), (max-height: 400px) {
.modal {
width: 90vw;
border-radius: 0;
}
}
/* Complex chaining with ranges */
@media screen and (min-width: 600px) and (max-width: 900px) and (min-resolution: 1dppx) {
/* Styles for medium-sized screens with standard resolution */
.layout {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
Note that commas create completely independent queries — if any one of the comma-separated conditions evaluates to true, the entire block applies. This is fundamentally different from chaining with and, which requires all conditions to be true simultaneously.
Range Syntax (Modern Shorthand)
Media Queries Level 4 introduces cleaner range syntax using familiar comparison operators. This is more readable than the traditional min- and max- prefix approach and is now supported in all modern browsers:
/* Traditional syntax */
@media (min-width: 768px) and (max-width: 1024px) { /* ... */ }
/* Modern range syntax — much cleaner */
@media (768px <= width <= 1024px) {
/* Styles for viewports between 768px and 1024px */
}
/* Additional range examples */
@media (width >= 1200px) {
/* Wide desktop styles */
}
@media (400px <= width <= 600px) {
/* Small tablet or large phone */
}
@media (height <= 500px) {
/* Short viewports */
}
The range syntax also works with other dimensional features like height, aspect-ratio, and resolution, making complex queries significantly easier to parse at a glance.
Best Practices for Mastering Media Queries
1. Embrace a Mobile-First Mindset
Start with the smallest screen as your default layout, then use min-width media queries to layer enhancements for larger viewports. This approach results in leaner, more performant CSS because mobile devices — often the most constrained — process only the base styles without having to override complex desktop rules:
/* Base: mobile (no query) */
.element { font-size: 1rem; }
/* Enhancement: tablet and up */
@media (min-width: 768px) {
.element { font-size: 1.1rem; }
}
/* Further enhancement: desktop */
@media (min-width: 1024px) {
.element { font-size: 1.2rem; }
}
2. Choose Breakpoints Based on Content, Not Devices
Don't blindly use breakpoints tied to specific devices (like "iPhone width" or "iPad width"). Instead, resize your browser and observe where your layout breaks — where text wraps awkwardly, columns become too narrow, or whitespace becomes excessive. Set breakpoints at those content-driven thresholds. This future-proofs your design against the constant stream of new device sizes.
/* Content-driven breakpoints — values determined by layout testing */
@media (min-width: 540px) { /* Navigation links fit on one row */ }
@media (min-width: 720px) { /* Cards can sit two-across comfortably */ }
@media (min-width: 960px) { /* Sidebar has enough room alongside content */ }
@media (min-width: 1200px) { /* Full multi-column layout viable */ }
3. Keep Media Queries Manageable and Modular
Rather than scattering media queries throughout your stylesheet, consider organizing them either inline near the relevant component or consolidated at the end of the file. For larger projects, CSS preprocessors like Sass or Less allow you to nest media queries inside selectors, keeping related styles visually grouped:
/* Sass nesting example — compiles to standard CSS */
.card {
padding: 16px;
background: #fff;
@media (min-width: 768px) {
padding: 24px;
display: flex;
gap: 20px;
}
@media (min-width: 1024px) {
padding: 32px;
max-width: 800px;
margin: 0 auto;
}
}
4. Use Relative Units Inside Media Queries
Breakpoints defined in pixels are fine, but the content inside media queries benefits tremendously from relative units like rem, em, vw, and percentages. This ensures that your responsive adjustments scale properly with user font-size preferences and zoom levels:
/* Breakpoint in px is standard, but internal rules use relative units */
@media (min-width: 768px) {
.text-block {
font-size: 1.125rem; /* Scales with root font size */
line-height: 1.6;
max-width: 65ch; /* Comfortable reading length */
margin-inline: auto;
}
}
5. Avoid Overly Specific Queries
A common pitfall is writing an excessive number of finely tuned media queries that target narrow device ranges. This creates a maintenance nightmare and often misses edge cases. Instead, let your layout naturally flex between breakpoints using fluid techniques like clamp(), min(), max(), and flexible grid/flexbox layouts:
/* Fluid typography that adapts smoothly without rigid breakpoints */
h1 {
font-size: clamp(1.5rem, 4vw + 1rem, 3rem);
}
/* Fluid container that never needs a media query */
.container {
width: min(100% - 2rem, 1200px);
margin-inline: auto;
}
6. Test Across Real Devices
Browser developer tools' responsive mode is a great starting point, but it cannot perfectly simulate every device. Test on physical phones, tablets, and laptops whenever possible. Pay special attention to:
- Touch vs. mouse interaction (consider
pointerandhovermedia features) - Viewport height variations caused by on-screen keyboards and browser chrome
- Actual rendering performance on lower-powered mobile CPUs
- Differences in how browsers handle
100vhon mobile (usedvhwhere supported)
7. Leverage Interaction Media Features
Beyond screen size, consider how users interact with your site. The pointer and hover media features let you fine-tune UI elements for touch vs. mouse input:
/* Enhance hover effects only when the device supports true hovering */
@media (hover: hover) {
.card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0,0,0,0.15);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
}
/* For coarse pointers (touch), increase tap target sizes */
@media (pointer: coarse) {
.nav-link {
padding: 12px 16px;
min-height: 44px; /* WCAG recommended minimum touch target */
}
}
/* Fine pointer (mouse/stylus) can have smaller, precise controls */
@media (pointer: fine) {
.color-picker-handle {
width: 8px;
height: 8px;
}
}
8. Combine with Container Queries for Component-Level Responsiveness
Media queries target the viewport globally, but sometimes you need a component to adapt based on its own container's size. The emerging Container Queries specification (now supported in all modern browsers) complements media queries perfectly:
/* Container query: component adapts to its parent's width, not the viewport */
.card-container {
container-type: inline-size;
}
@container (min-width: 400px) {
.card {
display: flex;
flex-direction: row;
align-items: center;
}
.card__image {
width: 40%;
}
}
@container (min-width: 600px) {
.card {
padding: 2rem;
border-radius: 12px;
}
}
Use media queries for page-level layout shifts (header, navigation, overall grid) and container queries for reusable components that need to look good in varying contexts regardless of the overall viewport size.
9. Use a Consistent Naming Convention and Document Breakpoints
In larger teams, establish a shared set of breakpoint variables (via CSS custom properties or preprocessor variables) and document them clearly. This prevents ad-hoc breakpoints from proliferating and ensures visual consistency across the codebase:
/* Define breakpoints as custom properties in a design tokens file */
:root {
--bp-sm: 540px;
--bp-md: 768px;
--bp-lg: 1024px;
--bp-xl: 1280px;
}
/* Reference breakpoints consistently — note: custom properties can't be used
directly inside @media, so this pattern works with preprocessors or you
manually reference the values. Consider using a CSS-in-JS solution or
PostCSS plugins that enable custom-property-based media queries. */
/* Example with Sass variables instead */
$bp-sm: 540px;
$bp-md: 768px;
$bp-lg: 1024px;
@media (min-width: $bp-md) {
/* ... */
}
10. Don't Forget the Print Experience
A well-crafted print stylesheet is often overlooked but adds significant polish. Use a print media query to strip unnecessary UI elements, adjust typography for readability on paper, and ensure proper contrast:
@media print {
/* Remove distractions */
nav, .sidebar, .advertisement, .comments-section {
display: none !important;
}
/* Ensure readable text */
body {
font-family: Georgia, serif;
font-size: 12pt;
line-height: 1.5;
color: #000;
background: #fff;
}
/* Expand links to show URLs */
a[href]::after {
content: " (" attr(href) ")";
font-size: 0.8em;
color: #555;
}
/* Avoid orphaned content */
h2, h3 {
break-after: avoid;
}
p {
orphans: 3;
widows: 3;
}
}
Conclusion
CSS Media Queries are far more than a responsive-design checkbox — they are a sophisticated conditional styling engine that adapts your site to the ever-expanding universe of devices, preferences, and contexts in which users experience the web. From the foundational min-width breakpoints that reshape layouts across screen sizes, to the nuanced prefers-reduced-motion and pointer queries that honor user needs and input modalities, mastering media queries means crafting experiences that feel intentional on every device.
The key to true mastery lies in combining thoughtful breakpoint selection, mobile-first architecture, fluid fallbacks, and the strategic use of modern Level 4 and 5 features. Pair media queries with container queries for component-level adaptability, use relative units for scalable interiors, and always test on real hardware. When you internalize these best practices, media queries transform from a blunt instrument into a precise, expressive tool that elevates both the design and the accessibility of everything you build. Start applying these techniques today, and watch your responsive designs become more robust, maintainable, and delightful across every screen.