Layout
Media Queries
Master CSS media queries, covering syntax rules, screen sizes, orientation properties, mobile-first min-width strategies, and breakpoints.
1. Learning Objectives
In this lesson, you will master writing CSS media queries. By the end of this topic, you will be able to:
- Identify media query components: media types, logical operators, and media features.
- Write mobile-first media queries using the
min-widthproperty. - Establish standard layout breakpoints for mobile, tablet, and desktop views.
- Configure media queries to detect landscape or portrait device orientation.
- Build custom print stylesheets to optimize layouts for printing on paper.
2. Overview
Media queries are a CSS feature that allows you to apply styles based on device characteristics, such as screen resolution, viewport width, or orientation. They form the foundation of responsive design, allowing you to tailor layouts to different screen sizes.
3. Why This Topic Matters
Media queries allow you to adjust layouts dynamically for different screen sizes:
- Overlapping CSS Rules: Misunderstanding how
min-widthandmax-widthrules cascade can cause media query styles to clash, leading to layout bugs. - Device-Specific Breakpoint Trap: Creating breakpoints for specific device screen widths (e.g. exactly 375px for iPhone) is hard to maintain. Breakpoints should be defined based on when the content layout itself breaks.
4. Real-World Analogy
Think of media queries like **setting dress code guidelines for a venue based on the weather**:
- The Venue Rule (Media Query): "If the temperature is 30°C or higher (min-width: 30deg), switch our outdoor guidelines to open the pool."
- Weather Conditions (Media Features): Checking the current temperature (viewport width) or if it's raining (media type: print) to update clothing styles (CSS properties) dynamically.
- Layered Outfit (Mobile-First styling): Starting with basic light clothing (mobile style). If the temperature drops below 15°C, put on a light jacket (tablet query). If it drops below 5°C, add a heavy coat (desktop query).
5. Core Concepts
A media query consists of an optional **media type** followed by **media features**:
- Media Types:
screen(for screens),print(for printed paper), orall(default). - Media Features: Expressions that test device conditions (e.g.
min-width: 768px,orientation: landscape). - Mobile-First Strategy (min-width): Declare base styles for mobile screens first (without media queries), then use
min-widthqueries to add styles as screen size increases.
| Breakpoint Tier | Min-Width Coordinate | Layout Target |
|---|---|---|
| Mobile (Base) | 0px to 639px | Stacked column elements, full-width blocks. |
| Tablet (md) | @media (min-width: 640px) |
Dual columns, compact dashboard views. |
| Desktop (lg) | @media (min-width: 1024px) |
Multi-column layouts with sidebars. |
6. Syntax & API Reference
Below is a CSS structure using a mobile-first media query approach:
7. Visual Diagram
This diagram displays how mobile-first min-width styles cascade and apply as the viewport expands:
8. Live Example — Full Working Code
A sample HTML document showcasing responsive columns and print stylesheet optimizations:
9. Interactive Playground
Try It Yourself Challenges:
- Resize your browser window past 768px and watch the border color change on the info card.
- Open the print preview dialog (Cmd+P or Ctrl+P) to verify how the print styles remove background colors and borders.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Overlapping min/max bounds | Using matching pixel values for min-width and max-width queries, causing styles to conflict at that exact width. | @media (max-width: 768px) {...} |
@media (max-width: 767px) {...} |
| Writing media queries in the wrong order | Placing larger min-width queries before smaller ones, causing the smaller queries to override them. | @media (min-width: 1024px) before @media (min-width: 768px) |
Order min-width queries from smallest to largest (ascending order). |
11. Best Practices
- Write mobile-first media queries: Design for mobile screens first, then use
min-widthqueries to add layout adjustments for larger viewports. - Order min-width queries from smallest to largest: Place media queries in ascending order (smallest to largest) in your stylesheet so they cascade correctly.
- Define breakpoints based on content: Choose breakpoints based on when your layout breaks, rather than targeting specific device screen sizes.
- Use relative units (em) for breakpoints: Declare media query width coordinates using
emunits (e.g.min-width: 48em) to ensure they scale correctly when users adjust browser zoom settings.
12. Browser Compatibility
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| Basic media queries support | Supported (21+) | Supported (3.5+) | Supported (4+) | Supported (12+) |
13. Interview Questions
🟢 Q1: Why is the mobile-first min-width approach preferred over max-width queries in modern responsive design?
Answer: The mobile-first (min-width) approach simplifies styling by establishing base styles for mobile screens first, then adding complexity as screen size increases. This leads to cleaner, more maintainable stylesheets. Using max-width queries often requires writing extra code to override desktop styles on smaller screens.
14. Debugging Exercise
Explain why the background color remains red on desktop viewports, and fix the CSS configuration:
Diagnosis: The media queries are out of order. Because min-width: 768px is declared after min-width: 1024px, it overrides the desktop rule on wider screens. To fix this, order the media queries in ascending order (smallest to largest).
Fixed CSS:
15. Practice Exercises
Exercise 1: Orientation Warning Overlay
Build a simple warning layout box. Use media queries to display the box only when a mobile device is rotated to landscape orientation.
16. Scenario-Based Challenge
The Paper Print Optimization Challenge:
Users complain that when they print article recipes from your blog, the output includes sidebar links, color headers, and footer banners, wasting paper ink. Propose an implementation plan using print media queries to clean up the printed output.
17. Quick Quiz
Q1: Which media type targets printed output on paper?
A) screen
B) print
C) all
Answer: B — The print media type applies styles only when a page is printed or viewed in print preview.
18. Summary & Key Takeaways
- • Design mobile layouts as the base style, then use min-width queries to add complexity for larger screens.
- • Place min-width media queries in ascending order (smallest to largest) in your stylesheet.
19. Cheat Sheet
| Query Template | Visual Layout Action |
|---|---|
@media (orientation: landscape) |
Applies styles only when the viewport width is greater than its height. |