Table of Contents
- What Are CSS Media Queries?
- Syntax of Media Queries
- Media Types
- Media Features
- Logical Operators
- Practical Examples
- Best Practices
- Common Pitfalls to Avoid
- Advanced Techniques
- Tools and Resources
- Conclusion
- Reference
What Are CSS Media Queries?
CSS Media Queries are a module of CSS that enable you to apply styles to a document based on the output device’s properties. In other words, they let you ask: “What kind of device is displaying this page, and what are its characteristics?” Then, you can tailor styles to match those conditions.
For example, you might use a media query to:
- Shrink font sizes on mobile devices for readability.
- Rearrange a grid layout from 1 column (mobile) to 3 columns (desktop).
- Hide navigation menus on printed pages.
- Adjust spacing when a device is rotated from portrait to landscape.
Media queries are defined using the @media rule, and they’ve been a core part of CSS since the CSS3 specification. Today, they’re supported by all modern browsers, making them a reliable tool for responsive design.
Syntax of Media Queries
The basic syntax of a media query is straightforward. It starts with the @media keyword, followed by an optional media type, one or more media features (enclosed in parentheses), and a set of CSS rules (enclosed in curly braces {}).
Here’s the general structure:
@media [media-type] ([media-feature]: [value]) {
/* CSS rules to apply when conditions are met */
}
Breakdown of Components:
@media: The at-rule that declares a media query.- Media Type: Optional. Specifies the category of device (e.g.,
screen,print). Defaults toallif omitted. - Media Feature: Required. Defines a specific characteristic to test (e.g.,
width,orientation). Must be wrapped in parentheses and include a value (e.g.,(max-width: 768px)). - CSS Rules: The styles to apply when the media query conditions are satisfied.
Example:
/* Apply styles to screens with a maximum width of 768px */
@media screen and (max-width: 768px) {
body {
font-size: 16px;
padding: 1rem;
}
}
Media Types
Media types categorize devices based on their primary use case. While early CSS specifications included many media types (e.g., tv, handheld, projection), most are now deprecated or rarely used. Modern responsive design focuses on just a few:
| Media Type | Description |
|---|---|
all | Applies to all devices (default if no media type is specified). |
screen | Applies to devices with a screen (e.g., smartphones, tablets, laptops). |
print | Applies to printed documents or print preview modes. |
speech | Applies to screen readers and other speech synthesizers. |
Key Notes:
- Omit the media type to target
alldevices (e.g.,@media (max-width: 768px)is equivalent to@media all and (max-width: 768px)). - Use
screenfor most responsive design tasks, as it targets devices with visual screens. printis useful for customizing how content appears when printed (e.g., hiding ads or navigation).
Media Features
Media features are the heart of media queries. They test specific device or viewport characteristics and return true or false. Most media features accept a min- or max- prefix to define a range (e.g., min-width, max-height).
Below are the most commonly used media features:
1. Width & Height
These features target the viewport’s width and height. They are the most frequently used media features for responsive design.
-
width: The viewport’s width. Usemin-width(minimum width) ormax-width(maximum width) to define ranges.- Example:
(min-width: 768px)– Applies when the viewport is at least 768px wide. - Example:
(max-width: 480px)– Applies when the viewport is 480px wide or smaller.
- Example:
-
height: The viewport’s height. Usemin-heightormax-heightfor ranges.- Example:
(min-height: 600px)– Applies when the viewport is at least 600px tall.
- Example:
2. Orientation
The orientation feature checks whether the device is in portrait or landscape mode.
portrait: Height > width (e.g., a smartphone held upright).landscape: Width > height (e.g., a smartphone rotated sideways).
Example:
/* Adjust layout when device is in landscape mode */
@media (orientation: landscape) {
.hero-image {
height: 80vh; /* 80% of viewport height */
}
}
3. Aspect Ratio
aspect-ratio tests the ratio of the viewport’s width to height. Use min-aspect-ratio or max-aspect-ratio for ranges.
- Syntax:
(aspect-ratio: width/height)(e.g.,16/9for widescreen,4/3for standard).
Example:
/* Target widescreen displays (16:9 or wider) */
@media (min-aspect-ratio: 16/9) {
.video-container {
grid-template-columns: 2fr 1fr; /* Wider video, narrower sidebar */
}
}
4. Device Pixel Ratio
device-pixel-ratio (or min-device-pixel-ratio) tests the ratio of physical pixels to logical pixels on a screen (e.g., Retina displays). Useful for serving high-resolution images.
Example:
/* Serve high-res images on Retina displays */
@media (min-device-pixel-ratio: 2) {
.logo {
background-image: url("[email protected]");
}
}
5. Color
color checks the number of bits per color component of the device. Use min-color to target devices with more color depth.
Example:
/* Apply styles only to color screens (not monochrome) */
@media (color) {
.alert {
color: #ff0000; /* Red text */
}
}
Other Useful Media Features:
hover: Tests if the device supports hover (e.g.,(hover: hover)for mice,(hover: none)for touchscreens).prefers-color-scheme: Checks if the user prefers alightordarkcolor scheme (system-level setting).@media (prefers-color-scheme: dark) { body { background: #1a1a1a; color: #ffffff; } }inverted-colors: Detects if the user has enabled inverted colors (e.g.,(inverted-colors: inverted)).
Logical Operators
Media queries can be combined or modified using logical operators to create more complex conditions. The most common operators are and, not, only, and comma-separated lists (for “or” logic).
1. and: Combine Conditions
Use and to chain media types and media features. All conditions must be true for the query to apply.
Example:
/* Apply to screen devices with width between 600px and 1024px */
@media screen and (min-width: 600px) and (max-width: 1024px) {
.card {
flex-direction: row; /* Horizontal layout on medium screens */
}
}
2. not: Negate a Query
not reverses the result of a media query. It only applies to the entire query (not individual features).
Example:
/* Apply to all devices EXCEPT print */
@media not print {
.header {
background: #f5f5f5; /* Keep background on screens */
}
}
3. only: Hide from Older Browsers
only prevents older browsers (that don’t support media queries) from misinterpreting the query. It has no effect on modern browsers.
Example:
/* Older browsers ignore this; modern browsers treat it as "screen and (max-width: 768px)" */
@media only screen and (max-width: 768px) {
.menu {
display: none; /* Hide menu on small screens */
}
}
4. Comma-Separated Lists: “Or” Logic
Use commas to separate media queries, creating an “or” condition (any one of the queries must be true).
Example:
/* Apply if viewport is < 480px OR device is in landscape orientation */
@media (max-width: 480px), (orientation: landscape) {
.content {
padding: 0.5rem; /* Reduce padding in small or landscape views */
}
}
Practical Examples
Let’s put media queries into action with real-world scenarios.
Example 1: Mobile-First Responsive Design
Mobile-first design starts with base styles for mobile devices, then adds media queries to enhance the layout for larger screens. This approach uses min-width to “layer up” styles.
/* Base styles (mobile-first: applies to all screens by default) */
body {
font-size: 14px;
margin: 0;
padding: 1rem;
}
.container {
display: flex;
flex-direction: column; /* Stack elements vertically on mobile */
gap: 1rem;
}
/* Tablet: 768px and up */
@media (min-width: 768px) {
body {
font-size: 16px;
padding: 2rem;
}
.container {
flex-direction: row; /* Side-by-side layout on tablets */
}
}
/* Desktop: 1200px and up */
@media (min-width: 1200px) {
body {
font-size: 18px;
padding: 3rem;
}
.container {
max-width: 1400px; /* Limit width on large screens */
margin: 0 auto;
}
}
Example 2: Print Styles
Customize how your page looks when printed by targeting the print media type.
/* Hide non-essential elements on print */
@media print {
header, nav, footer {
display: none;
}
/* Improve readability for print */
body {
background: white;
color: black;
font-size: 12pt;
margin: 0;
padding: 0;
}
/* Add page breaks between sections */
section {
page-break-after: always;
}
}
Example 3: Orientation Change
Adjust layout when a device is rotated between portrait and landscape.
/* Portrait: Stack elements vertically */
@media (orientation: portrait) {
.profile {
flex-direction: column;
text-align: center;
}
}
/* Landscape: Arrange elements horizontally */
@media (orientation: landscape) {
.profile {
flex-direction: row;
align-items: center;
gap: 2rem;
}
}
Best Practices
To write effective media queries, follow these best practices:
1. Use Mobile-First Design
Start with base styles for mobile devices, then add min-width media queries to enhance for larger screens. This approach ensures your site works on the smallest devices first and scales up, reducing unnecessary code for mobile users.
Why? Mobile-first is more efficient (smaller initial CSS payload) and aligns with the growing number of mobile users.
2. Choose Content-Based Breakpoints
Avoid targeting specific devices (e.g., @media (max-width: 375px) for iPhone SE). Instead, use breakpoints based on when your content needs to change (e.g., when text overflows or a grid becomes too cramped). Common breakpoints include:
360px(small mobile)768px(tablet)1024px(laptop)1440px(desktop)
3. Use Relative Units
Prefer em, rem, or % over fixed px for breakpoints and layout values. This ensures your design scales with user font size settings.
Example:
/* Use rem for breakpoints (1rem = 16px by default) */
@media (min-width: 48rem) { /* 768px */
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
4. Keep Media Queries Close to Related CSS
Group media queries with the base styles they modify (instead of dumping all queries at the end of your CSS). This makes your code easier to maintain.
Example:
/* Base button styles */
.btn {
padding: 0.5rem 1rem;
font-size: 1rem;
}
/* Responsive button styles */
@media (min-width: 48rem) {
.btn {
padding: 0.75rem 1.5rem;
font-size: 1.1rem;
}
}
5. Test on Real Devices
Emulators are helpful, but real devices often behave differently. Test on actual smartphones, tablets, and laptops to ensure your media queries work as expected.
Common Pitfalls to Avoid
Even experienced developers make mistakes with media queries. Watch out for these:
1. Incorrect Order of Queries
CSS is cascading: later rules override earlier ones if they have the same specificity. For mobile-first design (using min-width), list queries in ascending order (smallest to largest). For desktop-first (using max-width), list them in descending order (largest to smallest).
Mistake:
/* Desktop-first with queries in wrong order */
@media (max-width: 768px) { /* Applies to <768px */ }
@media (max-width: 1024px) { /* Applies to <1024px, but comes after, so overrides the 768px query for screens <768px! */ }
Fix:
/* Desktop-first: List max-width queries from largest to smallest */
@media (max-width: 1024px) { /* <1024px */ }
@media (max-width: 768px) { /* <768px (overrides 1024px styles for smaller screens) */ }
2. Forgetting the Viewport Meta Tag
Media queries rely on the browser knowing the device’s viewport width. Without the viewport meta tag, mobile browsers may zoom out, making your media queries ineffective.
Add this to your HTML <head>:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
3. Overusing Breakpoints
Too many breakpoints lead to bloated, hard-to-maintain code. Stick to 3–5 breakpoints unless your design truly requires more.
4. Using Fixed Units for Breakpoints
Avoid px for breakpoints if possible. If a user zooms in, px-based breakpoints won’t adjust, potentially breaking your layout. Use rem or em instead.
Advanced Techniques
Once you’ve mastered the basics, explore these advanced media query techniques:
1. Custom Media Queries (CSS Variables)
CSS Media Queries Level 5 introduces @custom-media, allowing you to define reusable media query variables. This keeps your code DRY (Don’t Repeat Yourself).
Example:
/* Define custom breakpoints */
@custom-media --small-screen (min-width: 360px) and (max-width: 767px);
@custom-media --large-screen (min-width: 1200px);
/* Use them later */
@media (--small-screen) {
.nav { display: none; }
}
@media (--large-screen) {
.sidebar { position: sticky; top: 2rem; }
}
Note: @custom-media is currently supported in Firefox and Chrome with experimental flags. For broader support, use a preprocessor like Sass.
2. Nesting Media Queries (Sass)
CSS preprocessors like Sass let you nest media queries inside selectors, making your code more readable.
Example (Sass):
.card {
padding: 1rem;
/* Nested media query */
@media (min-width: 768px) {
padding: 2rem;
border-radius: 8px;
}
}
3. Combining with CSS Grid/Flexbox
Media queries work seamlessly with modern layout tools like Grid and Flexbox. Use them to reorder, resize, or hide elements at different breakpoints.
Example:
.gallery {
display: grid;
grid-template-columns: repeat(1, 1fr); /* 1 column on mobile */
gap: 1rem;
}
@media (min-width: 768px) {
.gallery {
grid-template-columns: repeat(3, 1fr); /* 3 columns on tablets */
}
}
@media (min-width: 1200px) {
.gallery {
grid-template-columns: repeat(4, 1fr); /* 4 columns on desktops */
}
}
Tools and Resources
- Browser DevTools: Use Chrome’s Device Toolbar or Firefox’s Responsive Design Mode to test media queries.
- MDN Web Docs: Media Queries Guide – Official documentation.
- CSS-Tricks: Media Queries for Standard Devices – Reference for common breakpoints.
- Responsive Design Checker: BrowserStack – Test on real devices online.
- Sass: Sass Media Queries – For nesting and variables.
Conclusion
CSS Media Queries are the backbone of responsive web design, enabling your website to adapt to any device. By mastering their syntax, media features, and best practices, you can create layouts that look polished and functional everywhere—from smartphones to 4K monitors.
Remember: Start with mobile-first, use content-based breakpoints, test rigorously, and avoid common pitfalls like incorrect query order. With these skills, you’ll build websites that delight users, regardless of how they access your content.