Understanding Media Query Basics
CSS media queries are the foundation of responsive web design, enabling you to apply styles conditionally based on device characteristics, viewport dimensions, and user preferences. Understanding the logical operators that combine these conditions is essential for creating adaptive layouts that work seamlessly across all screen sizes and device types. Mastery of these techniques is a core skill in modern web development.
The @media At-Rule
The @media rule allows you to apply styles when specific conditions are met. The browser evaluates each media query as either true or false, and styles apply only when the query evaluates to true.
As explained in MDN Web Docs, media queries consist of a media type and one or more media features that describe specific characteristics of the device or viewport. When combined with logical operators, they create powerful conditional styling rules.
Media Types
Media types describe the general category of a device. While there are several types, only three are commonly used in modern web development.
| Media Type | Description |
|---|---|
screen | Devices with screens (monitors, phones, tablets) |
print | Printed output and print preview modes |
all | Matches any device (default when not specified) |
Note: Other media types like tv, handheld, and projection are deprecated and should not be used in new projects.
/* Target only screen devices */
@media screen {
.screen-content { display: block; }
}
/* Styles specifically for printing */
@media print {
.no-print { display: none; }
}
Understanding which media type to use helps you create more efficient stylesheets. According to Polypane's comprehensive guide, using the appropriate media type ensures your styles reach only the intended devices.
The AND Operator
The and operator combines multiple conditions, and the entire query evaluates to true only when every condition is satisfied. This is the most commonly used logical operator in responsive design.
/* Apply on screens between 600px and 900px wide */
@media screen and (min-width: 600px) and (max-width: 900px) {
.sidebar { display: block; }
}
/* Landscape orientation with minimum width */
@media (orientation: landscape) and (min-width: 768px) {
.hero { flex-direction: row; }
}
/* High-resolution displays on larger screens */
@media screen and (min-width: 1200px) and (resolution: 2dppx) {
.high-res-image { background-image: url('[email protected]'); }
}
When to Use AND
- Chaining multiple media features together
- Combining media type with specific features
- Creating complex breakpoint conditions
- Requiring both device type AND feature support
The AND operator gives you precise control over when styles apply. As noted in Web.dev's learning resources, combining conditions with AND creates more specific and intentional responsive behaviors. When building responsive layouts, pairing media query logic with proper CSS selector techniques ensures maintainable stylesheets.
The OR Operator (Comma Separators)
CSS uses commas to represent the OR operator. When any condition separated by commas evaluates to true, the entire rule applies. This is equivalent to writing multiple separate @media blocks.
/* Mobile OR tablet devices */
@media (max-width: 600px), (min-width: 601px) and (max-width: 1024px) {
.navigation { flex-direction: column; }
}
/* Very small OR very large screens */
@media (width <= 400px), (width >= 1440px) {
.special-banner { display: block; }
}
/* Print OR dark mode preference */
@media print, (prefers-color-scheme: dark) {
.theme-aware { background-color: var(--dark-background); }
}
Key Insight
The comma operator stops evaluating once a true condition is found. This can have performance implications for complex queries. Polypane's guide explains that understanding query evaluation order helps you write more efficient media queries.
The NOT Operator
The not operator negates an entire media query, applying styles when the query would otherwise be false. It must appear at the beginning of the query and requires careful consideration.
/* Apply to everything EXCEPT print */
@media not print {
.screen-only { display: block; }
}
/* Exclude small mobile devices */
@media not (max-width: 480px) {
.requires-space { display: grid; }
}
/* Exclude devices without hover capability */
@media not (hover: none) {
.hover-expectant { display: flex; }
}
Important Rules for NOT
- Must appear at the beginning of the query
- Must include a media type when using
not - De Morgan's laws apply:
not (A and B)=(not A) or (not B) - Not all browsers support
notfor every media feature
The MDN Web Docs provide detailed information on browser support for the NOT operator across different media features.
The ONLY Operator
The only operator prevents styles from applying in older browsers that don't fully support media query syntax. Modern browsers ignore styles wrapped in only when they don't match the rest of the query.
/* Only applies to screens (prevents old browser issues) */
@media only screen {
.modern-styles { display: flex; }
}
/* Combined with other conditions */
@media only screen and (min-width: 768px) {
.tablet-optimized { grid-template-columns: repeat(3, 1fr); }
}
Modern Relevance
While only was crucial for progressive enhancement in the early days of media queries, its importance has diminished as browser support has improved. However, it remains valid and can still serve as a clear indicator of intent in your code. Web.dev notes that modern development practices have largely rendered this operator historical, though it still has its place in ensuring backwards compatibility. Understanding these foundational CSS concepts pairs well with learning JavaScript loops and logic for comprehensive front-end development skills.
Modern Range Syntax
Modern CSS supports mathematical comparison operators for range features, making queries more readable and intuitive without min- or max- prefixes.
/* Traditional syntax */
@media (min-width: 600px) and (max-width: 1200px) {
/* Styles */
}
/* Modern range syntax */
@media (width >= 600px) and (width <= 1200px) {
/* Same effect, more readable */
}
/* Comparison operators for other features */
@media (height >= 800px) {
.tall-viewport { /* Styles */ }
}
@media (aspect-ratio > 1) {
/* Landscape orientation */
}
Browser Support
The <= and >= operators are widely supported in modern browsers. For projects requiring legacy browser support, stick with min- and max- prefixes. As documented in Web.dev's media query guide, the modern syntax offers improved readability without sacrificing functionality.
User Preference Media Features
Modern CSS provides media features for respecting user system preferences, enabling inclusive and accessible design.
/* Dark mode preference */
@media (prefers-color-scheme: dark) {
:root {
--background-color: #1a1a1a;
--text-color: #ffffff;
}
}
@media (prefers-color-scheme: light) {
:root {
--background-color: #ffffff;
--text-color: #1a1a1a;
}
}
/* Reduced motion for accessibility */
@media (prefers-reduced-motion: reduce) {
.animated-element {
animation: none;
transition: none;
}
}
/* High contrast mode */
@media (prefers-contrast: more) {
.high-contrast-text {
color: #000000;
background-color: #ffffff;
border: 2px solid #000000;
}
}
/* Reduced transparency */
@media (prefers-reduced-transparency: reduce) {
.translucent-overlay { opacity: 1; }
}
These user preference features are essential for building accessible websites. The MDN Web Docs provide a complete reference of all available preference-based media features. Implementing proper accessibility support is a hallmark of professional web development practices.
Essential patterns for effective responsive design
Content-First Breakpoints
Target your content's needs, not specific devices. Let the design break points emerge from your layout requirements.
Mobile-First Approach
Start with mobile styles as base, then enhance for larger screens using min-width queries for progressive improvement.
CSS Custom Properties
Combine media queries with CSS variables to create scalable, maintainable responsive design systems.
Performance Awareness
Stylesheets download regardless of query results. Keep selectors simple and avoid excessive specificity.
Common Pitfalls and How to Avoid Them
Mistake 1: Using OR Instead of AND
/* WRONG - This applies to ALL screens */
@media screen, (min-width: 768px) {
/* 'screen' matches everything! */
}
/* CORRECT - Use AND */
@media screen and (min-width: 768px) {
/* Only screens at least 768px wide */
}
Mistake 2: Forgetting Default Media Type
/* Implicit 'all' - works but less clear */
@media (min-width: 768px) { }
/* Explicit is better */
@media all and (min-width: 768px) { }
Mistake 3: Overlapping Breakpoints
/* Both match at exactly 768px - can cause conflicts */
@media (max-width: 768px) { /* Mobile */ }
@media (min-width: 768px) { /* Desktop */ }
/* Be intentional about which wins at breakpoints */
Avoiding these common mistakes ensures your responsive designs behave consistently across all devices and screen sizes.
Frequently Asked Questions
Conclusion
Mastering the logical operators in CSS media queries--and, or, not, and only--transforms responsive design from a series of breakpoints into a sophisticated system of conditional styling. Combined with modern range syntax and user preference features, these tools enable you to create websites that adapt gracefully to any device, any screen size, and any user's accessibility needs.
Key Takeaways:
- Use
andto combine multiple required conditions - Use comma-separated lists for OR logic
- Use
notto exclude specific conditions - Use
onlyfor legacy browser compatibility - Prefer modern range syntax (
>=,<=) for readability - Respect user preferences for accessibility
- Test across real devices and user settings
Start with simple queries, layer in complexity as needed, and always verify your responsive designs deliver consistent, high-quality experiences across all contexts. For more advanced responsive design techniques, explore our web development services to learn how we build adaptive, performant websites.
Sources
- MDN Web Docs: Using media queries - Official syntax reference for media types, features, and logical operators
- Polypane: The complete guide to CSS media queries - In-depth logical operator patterns and advanced usage
- Web.dev: Media queries - Responsive design best practices and performance considerations