0
0
CSSmarkup~15 mins

Media queries in CSS - Deep Dive

Choose your learning style9 modes available
Overview - Media queries
What is it?
Media queries are a way to make websites look good on different screen sizes and devices. They let you apply different styles depending on things like screen width, height, or device type. This helps create responsive designs that adapt to phones, tablets, and desktops. Without media queries, websites would look the same everywhere, often breaking or being hard to use on small screens.
Why it matters
Media queries solve the problem of one-size-fits-all web design. Without them, users on small phones would have to zoom and scroll a lot, making websites frustrating. They allow designers to tailor layouts and fonts for each device, improving usability and accessibility. This means better user experience, more visitors staying longer, and websites that work well everywhere.
Where it fits
Before learning media queries, you should understand basic CSS and how styles apply to HTML elements. After media queries, you can learn advanced responsive design techniques like flexible grids, CSS variables, and modern layout systems like Flexbox and Grid.
Mental Model
Core Idea
Media queries let your website listen to the device's screen and change its style to fit perfectly.
Think of it like...
It's like choosing clothes based on the weather: you wear a jacket if it's cold and shorts if it's hot. Media queries help your website 'dress' itself right for the screen size.
┌─────────────────────────────┐
│        Device Screen         │
│ ┌───────────────┐           │
│ │ Media Query   │  Checks   │
│ │ Conditions    │──────────▶│
│ └───────────────┘           │
│                             │
│ Applies matching CSS styles  │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat are media queries
🤔
Concept: Introduce the basic idea of media queries as CSS rules that apply only under certain conditions.
Media queries are special CSS rules that only work if the device matches certain features. For example, you can write CSS that only applies if the screen is smaller than 600 pixels wide. This lets you change how your page looks on small screens without changing the HTML.
Result
You can write CSS that changes styles based on screen size or device features.
Understanding that CSS can react to device features is the foundation for making websites that adapt to different screens.
2
FoundationBasic syntax of media queries
🤔
Concept: Learn how to write a simple media query using @media and conditions.
A media query starts with @media, followed by a condition in parentheses, then curly braces with CSS inside. For example: @media (max-width: 600px) { body { background-color: lightblue; } } This means: if the screen width is 600 pixels or less, make the background light blue.
Result
The background color changes only on small screens.
Knowing the syntax lets you start writing your own responsive styles easily.
3
IntermediateUsing multiple conditions
🤔Before reading on: do you think you can combine conditions with AND, OR, or NOT in media queries? Commit to your answer.
Concept: Learn how to combine multiple conditions using logical operators like and, or, and not.
You can combine conditions to be more specific. For example: @media (min-width: 400px) and (max-width: 800px) { p { font-size: 1.2rem; } } This applies styles only if the screen is between 400 and 800 pixels wide. You can also use commas to separate queries, which means OR: @media (max-width: 400px), (orientation: portrait) { body { color: red; } } This applies if either condition is true.
Result
Styles apply only when all AND conditions are true or any OR condition is true.
Combining conditions lets you target very specific device features and screen sizes.
4
IntermediateCommon media features to use
🤔
Concept: Explore the most useful features like width, height, orientation, resolution, and pointer.
Media queries can check many features: - width and height: screen size - orientation: portrait or landscape - resolution: screen pixel density - pointer: if the device has a fine pointer like a mouse or coarse like a finger Example: @media (orientation: landscape) { nav { display: flex; } } This applies styles when the device is wider than tall.
Result
You can adapt layouts for different device capabilities and orientations.
Knowing which features to check helps you design for real user environments, not just screen size.
5
IntermediateMedia queries in CSS vs HTML
🤔
Concept: Understand where media queries live and how they differ in CSS files and HTML link tags.
Media queries are mostly used inside CSS files with @media rules. But you can also use them in HTML to load different CSS files: This loads small.css only on small screens. This method helps reduce CSS loaded on devices that don't need it.
Result
You can control which CSS files load based on device features.
Knowing both methods helps optimize performance and maintainability.
6
AdvancedMobile-first vs desktop-first strategies
🤔Before reading on: do you think writing media queries starting from small screens or large screens is better? Commit to your answer.
Concept: Learn the two main approaches to writing media queries and their pros and cons.
Mobile-first means writing base CSS for small screens, then adding media queries for larger screens: body { font-size: 1rem; } @media (min-width: 600px) { body { font-size: 1.2rem; } } Desktop-first is the opposite, starting with large screens and adding queries for smaller ones: body { font-size: 1.2rem; } @media (max-width: 599px) { body { font-size: 1rem; } } Mobile-first is recommended because it matches how most users access the web and works better with progressive enhancement.
Result
You choose a strategy that affects how you organize your CSS and media queries.
Understanding these strategies helps you write cleaner, more efficient responsive CSS.
7
ExpertAdvanced media features and future-proofing
🤔Before reading on: do you think media queries can detect user preferences like dark mode or reduced motion? Commit to your answer.
Concept: Explore advanced media features like prefers-color-scheme and prefers-reduced-motion, and how to write future-proof queries.
Modern media queries can detect user preferences: @media (prefers-color-scheme: dark) { body { background: black; color: white; } } @media (prefers-reduced-motion: reduce) { * { animation: none; } } Also, use feature queries and logical operators to write queries that adapt as new devices appear. For example, using ranges and combining conditions carefully avoids breaking on unknown screen sizes.
Result
Your website can respect user system settings and be ready for future devices.
Knowing these advanced features lets you build accessible, user-friendly, and future-ready websites.
Under the Hood
When a browser loads a webpage, it checks the device's characteristics like screen size and resolution. It then evaluates each media query condition in the CSS. If the condition matches, the browser applies the styles inside that media query block. This happens dynamically, so if the user resizes the window or rotates the device, the browser reevaluates and updates styles instantly.
Why designed this way?
Media queries were created to solve the problem of fixed-size web designs that didn't work well on all devices. The web was growing beyond desktop screens to phones and tablets. The design needed a way to adapt styles based on device features without changing HTML or requiring separate sites. Media queries provide a flexible, declarative way to do this purely in CSS.
┌───────────────┐
│ Browser loads │
│ webpage       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Detect device │
│ features      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Evaluate each │
│ media query   │
│ condition     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Apply matching│
│ CSS styles    │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: do media queries change the HTML structure or just the styles? Commit to your answer.
Common Belief:Media queries can change the HTML layout by adding or removing elements.
Tap to reveal reality
Reality:Media queries only change CSS styles; they cannot add, remove, or change HTML elements.
Why it matters:Expecting media queries to alter HTML leads to confusion and poor design choices. Structural changes require JavaScript or server-side code.
Quick: do media queries only work on screen size? Commit to yes or no.
Common Belief:Media queries only check screen width and height.
Tap to reveal reality
Reality:Media queries can check many features like orientation, resolution, pointer type, and user preferences, not just size.
Why it matters:Limiting media queries to size misses opportunities to improve accessibility and user experience.
Quick: do media queries always work perfectly on all devices? Commit to yes or no.
Common Belief:Media queries guarantee perfect responsive design on every device.
Tap to reveal reality
Reality:Media queries depend on device reporting accurate features and can behave differently on some browsers or devices.
Why it matters:Assuming perfect behavior can cause bugs and layout issues on rare devices or browsers.
Quick: do media queries load all CSS files regardless of conditions? Commit to yes or no.
Common Belief:All CSS files linked in HTML load regardless of media query conditions.
Tap to reveal reality
Reality:CSS files linked with media attributes only load if their media query matches, saving bandwidth.
Why it matters:Understanding this helps optimize performance by loading only needed CSS.
Expert Zone
1
Media queries can be combined with CSS custom properties to create dynamic themes that adjust smoothly across breakpoints.
2
The order of media queries in CSS matters; later rules override earlier ones if conditions overlap, so careful ordering prevents conflicts.
3
Some devices report unusual or inconsistent feature values (like viewport width), so testing on real devices is essential to avoid surprises.
When NOT to use
Media queries are not suitable for changing content structure or loading different content; use JavaScript or server-side rendering for that. Also, avoid relying solely on media queries for accessibility; combine with semantic HTML and ARIA roles.
Production Patterns
In production, media queries are often used with mobile-first CSS frameworks, combined with Flexbox and Grid layouts. Developers use them to create fluid grids, hide or show navigation menus, and adjust typography for readability. They also use prefers-color-scheme queries to implement dark mode automatically.
Connections
Progressive enhancement
Media queries build on progressive enhancement by allowing basic styles first, then adding enhancements for capable devices.
Understanding media queries helps grasp how to design websites that work everywhere but improve on better devices.
User accessibility preferences
Media queries can detect user system preferences like reduced motion or dark mode, connecting design to accessibility needs.
Knowing media queries helps you respect user comfort and accessibility settings automatically.
Biology: human adaptation to environment
Just like humans adapt clothing and behavior to weather and surroundings, media queries adapt website styles to device environments.
Seeing media queries as environmental adaptation deepens understanding of responsive design as a natural, user-centered process.
Common Pitfalls
#1Writing media queries with max-width but forgetting to test overlapping ranges.
Wrong approach:@media (max-width: 600px) { body { font-size: 1rem; } } @media (max-width: 800px) { body { font-size: 1.2rem; } }
Correct approach:@media (max-width: 600px) { body { font-size: 1rem; } } @media (min-width: 601px) and (max-width: 800px) { body { font-size: 1.2rem; } }
Root cause:Overlapping media query ranges cause conflicting styles and unpredictable results.
#2Using fixed pixel values without considering device pixel ratio or zoom.
Wrong approach:@media (max-width: 320px) { p { font-size: 12px; } }
Correct approach:@media (max-width: 20rem) { p { font-size: 0.75rem; } }
Root cause:Using pixels ignores user zoom and device scaling, reducing accessibility and flexibility.
#3Placing media queries inside CSS selectors incorrectly.
Wrong approach:p { color: black; @media (max-width: 600px) { color: red; } }
Correct approach:@media (max-width: 600px) { p { color: red; } }
Root cause:Media queries must wrap selectors, not be nested inside them; CSS syntax does not allow nesting.
Key Takeaways
Media queries let your website adapt its style based on device features like screen size and orientation.
They are written using @media rules with conditions that the browser checks to apply styles dynamically.
Combining multiple conditions and using features beyond size allows precise control over responsive design.
Mobile-first is the recommended strategy for writing media queries to build flexible and efficient CSS.
Advanced media queries can respect user preferences like dark mode and reduced motion, improving accessibility.