Media queries are a cornerstone of responsive web design, allowing developers to apply styles based on device characteristics. Here's how to master them:
What Are Media Queries?
Media queries let you customize CSS based on conditions like:
- Screen width/height
- Orientation (portrait/landscape)
- Resolution
- Color depth
- Device type
🎯 Example:
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
Syntax Essentials
Use this structure to target specific conditions:
@media [media_type] and ([condition]) {
/* CSS rules */
}
💡 Pro Tip: Always test queries with browser developer tools to visualize layout changes.
Common Use Cases
- Mobile-first design
@media (min-width: 768px) { /* Styles for tablets/desktops */ }
- Orientation changes
@media (orientation: landscape) { .sidebar { display: block; } }
- High-resolution screens
@media (min-resolution: 2dppx) { img { width: 100%; } }
Best Practices
- Use
max-width
instead ofmin-width
for flexible layouts - Combine multiple conditions with
and
- Keep media query logic simple and maintainable
- Test on real devices or simulators
For deeper insights, check our CSS Flexbox Guide to understand how it complements media queries.