A comprehensive guide to CSS media queries for responsive web design, explaining how they enable adaptive layouts and styling based on device characteristics, screen dimensions, and user preferences.
Media queries are a fundamental CSS feature that allows web content to adapt to different devices, screen sizes, and user preferences. They form the backbone of responsive web design, enabling developers to create websites that provide optimal viewing experiences across a wide range of devices from desktop computers to mobile phones. Media queries are particularly crucial for color management, theme switching, and accessibility features in modern web development.
Media queries use the @media rule to apply different styles based on various conditions:
/* Basic media query syntax */
@media screen and (max-width: 768px) {
/* CSS rules that apply when viewport width is 768px or less */
body {
font-size: 14px;
background-color: #f8f9fa;
}
}
/* Multiple conditions */
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* Styles for tablet devices */
.container {
max-width: 750px;
padding: 20px;
}
}
/* Logical operators */
@media screen and (max-width: 600px), print {
/* Applies to small screens OR print media */
.navigation {
display: none;
}
}Media queries consist of several key components:
Different media types for various output devices:
/* Screen devices (default) */
@media screen {
body {
background-color: white;
color: black;
}
}
/* Print styles */
@media print {
body {
background-color: white;
color: black;
font-size: 12pt;
}
.no-print {
display: none;
}
}
/* Speech synthesis */
@media speech {
body {
voice-family: male;
voice-rate: medium;
}
}
/* All media types */
@media all {
/* Universal styles */
* {
box-sizing: border-box;
}
}Width and height-based media queries for responsive layouts:
/* Viewport width queries */
@media (max-width: 480px) {
/* Mobile phones */
.container {
width: 100%;
padding: 10px;
}
}
@media (min-width: 481px) and (max-width: 768px) {
/* Tablets */
.container {
width: 90%;
padding: 15px;
}
}
@media (min-width: 769px) and (max-width: 1024px) {
/* Small desktops */
.container {
width: 80%;
padding: 20px;
}
}
@media (min-width: 1025px) {
/* Large desktops */
.container {
width: 70%;
max-width: 1200px;
padding: 30px;
}
}
/* Viewport height queries */
@media (max-height: 600px) {
/* Short viewports */
.header {
height: 60px;
}
.main-content {
padding-top: 10px;
}
}
@media (min-height: 800px) {
/* Tall viewports */
.header {
height: 100px;
}
.main-content {
padding-top: 40px;
}
}Modern media queries for user color preferences:
/* Light mode (default) */
@media (prefers-color-scheme: light) {
:root {
--bg-color: #ffffff;
--text-color: #000000;
--accent-color: #007bff;
--border-color: #e9ecef;
--shadow-color: rgba(0, 0, 0, 0.1);
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #1a1a1a;
--text-color: #ffffff;
--accent-color: #66b3ff;
--border-color: #333333;
--shadow-color: rgba(255, 255, 255, 0.1);
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
/* Adjust images for dark mode */
img {
opacity: 0.8;
transition: opacity 0.3s ease;
}
img:hover {
opacity: 1;
}
}
/* No preference - provide both options */
@media (prefers-color-scheme: no-preference) {
/* Default to light mode or provide toggle */
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
}Accessibility-focused contrast media queries:
/* High contrast mode */
@media (prefers-contrast: high) {
:root {
--bg-color: #000000;
--text-color: #ffffff;
--accent-color: #ffff00;
--border-color: #ffffff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
/* Increase border thickness */
.card, .button, input {
border: 2px solid var(--border-color);
}
/* Remove subtle effects */
.shadow {
box-shadow: none;
}
/* High contrast buttons */
.button {
background-color: var(--text-color);
color: var(--bg-color);
border: 2px solid var(--accent-color);
}
}
/* Low contrast preference */
@media (prefers-contrast: low) {
:root {
--text-color: #666666;
--border-color: #f0f0f0;
}
/* Softer colors */
body {
color: var(--text-color);
}
.card {
border: 1px solid var(--border-color);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
}Media queries for different color capabilities:
/* Standard sRGB color space */
@media (color-gamut: srgb) {
.vibrant-image {
filter: saturate(1.1);
}
}
/* P3 wide color gamut */
@media (color-gamut: p3) {
.vibrant-image {
/* Use P3 colors for wider gamut displays */
background: color(display-p3 1 0.5 0);
}
}
/* Rec2020 ultra-wide color gamut */
@media (color-gamut: rec2020) {
.vibrant-image {
/* Use Rec2020 colors for ultra-wide gamut displays */
background: color(rec2020 1 0.5 0);
}
}
/* Color depth queries */
@media (color: 8) {
/* 8-bit color depth (256 colors per channel) */
.gradient {
background: linear-gradient(45deg, #ff0000, #0000ff);
}
}
@media (color: 16) {
/* 16-bit color depth (65536 colors per channel) */
.gradient {
background: linear-gradient(
45deg,
color(display-p3 1 0 0),
color(display-p3 0 0 1)
);
}
}Queries for device orientation changes:
/* Portrait orientation */
@media (orientation: portrait) {
.layout {
flex-direction: column;
}
.sidebar {
width: 100%;
order: 2;
}
.main-content {
order: 1;
}
/* Adjust colors for portrait */
.hero-section {
background: linear-gradient(
to bottom,
#667eea,
#764ba2
);
}
}
/* Landscape orientation */
@media (orientation: landscape) {
.layout {
flex-direction: row;
}
.sidebar {
width: 300px;
order: 1;
}
.main-content {
flex: 1;
order: 2;
}
/* Adjust colors for landscape */
.hero-section {
background: linear-gradient(
to right,
#667eea,
#764ba2
);
}
}Media queries for different screen resolutions:
/* Standard resolution */
@media (resolution: 96dpi) {
.icon {
background-image: url('icon-1x.png');
}
}
/* High DPI displays (Retina) */
@media (min-resolution: 192dpi) {
.icon {
background-image: url('icon-2x.png');
background-size: 24px 24px;
}
}
/* Ultra-high DPI displays */
@media (min-resolution: 288dpi) {
.icon {
background-image: url('icon-3x.png');
background-size: 24px 24px;
}
}
/* Device pixel ratio queries */
@media (-webkit-min-device-pixel-ratio: 2) {
/* WebKit-based browsers */
.retina-image {
background-image: url('image@2x.jpg');
background-size: 100% 100%;
}
}
@media (min-device-pixel-ratio: 2) {
/* Standard syntax */
.retina-image {
background-image: url('image@2x.jpg');
background-size: 100% 100%;
}
}Respecting user motion preferences:
/* Default animations */
.animated-element {
transition: all 0.3s ease;
animation: slideIn 0.5s ease-out;
}
/* Reduced motion preference */
@media (prefers-reduced-motion: reduce) {
.animated-element {
transition: none;
animation: none;
}
/* Provide alternative feedback */
.button:hover {
background-color: #007bff;
color: white;
/* No transition, instant change */
}
/* Disable parallax effects */
.parallax {
transform: none !important;
}
/* Simplify complex animations */
.loading-spinner {
animation: none;
background-color: #007bff;
}
.loading-spinner::after {
content: "Loading...";
}
}
/* No motion preference */
@media (prefers-reduced-motion: no-preference) {
/* Enhanced animations for users who enjoy motion */
.enhanced-animation {
animation: complexSlideIn 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
}Media queries for transparency and opacity preferences:
/* Reduced transparency */
@media (prefers-reduced-transparency: reduce) {
.glass-effect {
background-color: #ffffff;
backdrop-filter: none;
opacity: 1;
}
.modal-overlay {
background-color: #000000;
opacity: 0.8;
}
/* Remove subtle transparency effects */
.card {
background-color: #ffffff;
opacity: 1;
}
}
/* No transparency preference */
@media (prefers-reduced-transparency: no-preference) {
.glass-effect {
background-color: rgba(255, 255, 255, 0.8);
backdrop-filter: blur(10px);
}
.modal-overlay {
background-color: rgba(0, 0, 0, 0.5);
}
}Modern container-based queries for component-level responsiveness:
/* Container query setup */
.card-container {
container-type: inline-size;
container-name: card;
}
/* Container queries */
@container card (min-width: 300px) {
.card {
display: flex;
flex-direction: row;
}
.card-image {
width: 40%;
}
.card-content {
width: 60%;
padding: 20px;
}
}
@container card (max-width: 299px) {
.card {
display: block;
}
.card-image {
width: 100%;
}
.card-content {
padding: 15px;
}
}Using media queries for feature detection:
/* Hover capability detection */
@media (hover: hover) {
/* Device can hover (mouse, trackpad) */
.button:hover {
background-color: #0056b3;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
}
@media (hover: none) {
/* Touch devices without hover */
.button:active {
background-color: #0056b3;
transform: scale(0.98);
}
}
/* Pointer precision detection */
@media (pointer: fine) {
/* Precise pointing device (mouse) */
.clickable {
padding: 8px 12px;
font-size: 14px;
}
}
@media (pointer: coarse) {
/* Imprecise pointing device (touch) */
.clickable {
padding: 12px 16px;
font-size: 16px;
min-height: 44px; /* iOS accessibility guideline */
}
}Using JavaScript to work with media queries:
// Media query list creation and handling
class MediaQueryManager {
constructor() {
this.queries = new Map();
this.setupQueries();
}
// Setup common media queries
setupQueries() {
const queries = {
mobile: '(max-width: 768px)',
tablet: '(min-width: 769px) and (max-width: 1024px)',
desktop: '(min-width: 1025px)',
darkMode: '(prefers-color-scheme: dark)',
lightMode: '(prefers-color-scheme: light)',
reducedMotion: '(prefers-reduced-motion: reduce)',
highContrast: '(prefers-contrast: high)',
portrait: '(orientation: portrait)',
landscape: '(orientation: landscape)',
retina: '(min-resolution: 192dpi)'
};
Object.entries(queries).forEach(([name, query]) => {
this.addQuery(name, query);
});
}
// Add a media query with callback
addQuery(name, queryString, callback = null) {
const mediaQuery = window.matchMedia(queryString);
const queryData = {
mediaQuery,
callbacks: callback ? [callback] : [],
matches: mediaQuery.matches
};
// Add listener
mediaQuery.addEventListener('change', (e) => {
queryData.matches = e.matches;
queryData.callbacks.forEach(cb => cb(e.matches, name));
});
this.queries.set(name, queryData);
return this;
}
// Add callback to existing query
onMatch(queryName, callback) {
const query = this.queries.get(queryName);
if (query) {
query.callbacks.push(callback);
// Call immediately with current state
callback(query.matches, queryName);
}
return this;
}
// Check if query matches
matches(queryName) {
const query = this.queries.get(queryName);
return query ? query.matches : false;
}
// Get current breakpoint
getCurrentBreakpoint() {
if (this.matches('mobile')) return 'mobile';
if (this.matches('tablet')) return 'tablet';
if (this.matches('desktop')) return 'desktop';
return 'unknown';
}
// Get user preferences
getUserPreferences() {
return {
colorScheme: this.matches('darkMode') ? 'dark' : 'light',
reducedMotion: this.matches('reducedMotion'),
highContrast: this.matches('highContrast'),
orientation: this.matches('portrait') ? 'portrait' : 'landscape',
isRetina: this.matches('retina')
};
}
}
// Usage example
const mqManager = new MediaQueryManager();
// Listen for breakpoint changes
mqManager.onMatch('mobile', (matches) => {
if (matches) {
document.body.classList.add('mobile-layout');
console.log('Switched to mobile layout');
} else {
document.body.classList.remove('mobile-layout');
}
});
// Listen for dark mode changes
mqManager.onMatch('darkMode', (matches) => {
document.body.classList.toggle('dark-theme', matches);
updateThemeColors(matches ? 'dark' : 'light');
});
// Theme color management
function updateThemeColors(theme) {
const root = document.documentElement;
if (theme === 'dark') {
root.style.setProperty('--bg-color', '#1a1a1a');
root.style.setProperty('--text-color', '#ffffff');
root.style.setProperty('--accent-color', '#66b3ff');
} else {
root.style.setProperty('--bg-color', '#ffffff');
root.style.setProperty('--text-color', '#000000');
root.style.setProperty('--accent-color', '#007bff');
}
}
// Responsive image loading
function loadResponsiveImage(element) {
const breakpoint = mqManager.getCurrentBreakpoint();
const isRetina = mqManager.matches('retina');
let imagePath = element.dataset.src;
// Adjust for breakpoint
if (breakpoint === 'mobile') {
imagePath = imagePath.replace('.jpg', '-mobile.jpg');
} else if (breakpoint === 'tablet') {
imagePath = imagePath.replace('.jpg', '-tablet.jpg');
}
// Adjust for retina
if (isRetina) {
imagePath = imagePath.replace('.jpg', '@2x.jpg');
}
element.src = imagePath;
}Designing for mobile devices first, then enhancing for larger screens:
/* Mobile-first base styles */
.container {
width: 100%;
padding: 15px;
background-color: #f8f9fa;
}
.navigation {
display: none; /* Hidden by default on mobile */
}
.mobile-menu {
display: block;
}
/* Tablet and up */
@media (min-width: 768px) {
.container {
max-width: 750px;
margin: 0 auto;
padding: 20px;
}
.navigation {
display: flex;
}
.mobile-menu {
display: none;
}
}
/* Desktop and up */
@media (min-width: 1024px) {
.container {
max-width: 1200px;
padding: 30px;
}
.sidebar {
display: block;
width: 300px;
}
}Optimizing media queries for better performance:
Industry-standard breakpoints for responsive design:
/* Common breakpoint system */
:root {
--breakpoint-xs: 0;
--breakpoint-sm: 576px;
--breakpoint-md: 768px;
--breakpoint-lg: 992px;
--breakpoint-xl: 1200px;
--breakpoint-xxl: 1400px;
}
/* Extra small devices (phones) */
@media (max-width: 575.98px) {
.container {
max-width: 100%;
}
}
/* Small devices (landscape phones) */
@media (min-width: 576px) {
.container {
max-width: 540px;
}
}
/* Medium devices (tablets) */
@media (min-width: 768px) {
.container {
max-width: 720px;
}
}
/* Large devices (desktops) */
@media (min-width: 992px) {
.container {
max-width: 960px;
}
}
/* Extra large devices (large desktops) */
@media (min-width: 1200px) {
.container {
max-width: 1140px;
}
}
/* Extra extra large devices (larger desktops) */
@media (min-width: 1400px) {
.container {
max-width: 1320px;
}
}Using browser tools to test media queries:
Comprehensive testing approaches for media queries:
New media query features in development:
Upcoming features in the CSS specification:
/* Range syntax (Level 5) */
@media (width >= 768px) {
/* Equivalent to min-width: 768px */
}
@media (400px <= width <= 800px) {
/* Equivalent to (min-width: 400px) and (max-width: 800px) */
}
/* Custom media queries */
@custom-media --mobile (max-width: 768px);
@custom-media --desktop (min-width: 1024px);
@media (--mobile) {
/* Use custom media query */
}
/* Environment queries (proposed) */
@media (light-level: dim) {
/* Adjust for low light conditions */
body {
background-color: #1a1a1a;
color: #ffffff;
}
}Media queries are essential for creating responsive, accessible, and user-friendly web experiences. They enable developers to adapt content presentation based on device capabilities, user preferences, and environmental conditions. Understanding media queries is crucial for modern web development, especially when working with color schemes, accessibility features, and responsive layouts.
As web technologies continue to evolve, media queries are becoming more sophisticated, offering greater control over how content adapts to different contexts. By mastering media queries, developers can create websites that provide optimal experiences for all users, regardless of their device, preferences, or accessibility needs.
The future of media queries promises even more powerful capabilities, including container queries, enhanced user preference detection, and environmental awareness, making them an increasingly important tool in the web developer's toolkit.
Explore these comprehensive pillar articles related to Media Queries
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Discover more about Media Queries and related color theory concepts
A comprehensive guide to color theory, its fundamental principles, and practical applications in digital design and web development.
A comprehensive guide to monochromatic color schemes - sophisticated single-hue harmonies that create unified visual experiences through systematic variations in saturation, lightness, and tonal relationships, essential for elegant design compositions, brand consistency, and advanced color theory applications requiring cohesive aesthetic unity.
Comprehensive guide to analogous color schemes - adjacent hues on the color wheel that create natural harmony, visual cohesion, and sophisticated design solutions through subtle color relationships and graduated transitions.
Comprehensive guide to complementary colors - opposing hues on the color wheel that create maximum visual contrast, dynamic tension, and powerful design impact through scientific color relationships and perceptual phenomena.
A comprehensive guide to split-complementary color schemes - sophisticated three-color harmonies that combine a base color with two colors adjacent to its complement, creating balanced visual contrast with reduced tension compared to direct complementary pairs, essential for refined design compositions, brand identity systems, and advanced color theory applications.
A comprehensive guide to tetradic color schemes - sophisticated four-color harmonies that use two complementary pairs arranged in rectangular or square formations on the color wheel, providing maximum color variety while maintaining structured relationships essential for dynamic design compositions, brand systems, and advanced color theory applications.
Discover more color terminology and concepts in our comprehensive glossary.
Browse Full Glossary