Media queries in React JS
Course: React JS Training
Topic: Media queries
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Introduction: Why One Layout Is Not Enough
People open the same web page from phones, tablets, laptops and very large monitors. A page designed for a wide desktop screen feels cramped and unreadable on a phone, and a page designed only for phones wastes most of a large monitor. Building a separate website for every screen size is not realistic, so modern web development follows one rule: write the HTML once, and let the CSS adapt the layout to whatever screen is viewing it.
This idea is called responsive web design, and its central tool is the media query. A media query lets you write CSS rules that apply only when certain conditions are true, for example "only when the window is at least 700 pixels wide" or "only when the user is printing the page". Without media queries, CSS applies the same rules everywhere; with them, your stylesheet becomes a set of conditional instructions that respond to the viewing situation.
For learners heading towards React, this topic matters more than it first appears. React components still render HTML and are still styled with CSS, so a React dashboard or product page must behave correctly at every screen size. Media queries remain the standard way to achieve that, whether the styles live in a plain CSS file, a CSS module, or inside a component.
2. What Is a Media Query in Simple Words
In plain words, a media query is a question the browser asks before using a block of CSS. The question has the form "does the current viewing situation match these conditions?" If the answer is yes, the styles inside the block are applied; if the answer is no, the browser simply skips that block and moves on.
A media query is a conditional wrapper around CSS rules: the rules inside are used only when the stated conditions about the device, screen or user preferences are true.
Think of a signboard that says "Swimming pool: adults only after 6 pm". The pool is the same pool; the rule that applies changes depending on who is asking and when. Similarly, you write one stylesheet, but different rules inside it activate for different screens and situations.
Two clarifications that save beginners a lot of confusion:
- A media query adds no new styling power. Everything inside a media query is ordinary CSS that you already know. The query only controls when those rules are active.
- A media query is evaluated live. If you drag the browser window narrower, the browser re-checks the conditions continuously and switches styles the moment a condition stops matching. No JavaScript is needed.
3. Key Terms Explained
Before writing media queries, get comfortable with the vocabulary. These words appear in every tutorial, documentation page and code review on responsive design.
| Term | Plain meaning |
| Viewport | The visible area of the page in the browser window or device screen. On a phone, it is the part of the page you can see without scrolling. |
@media at-rule | The CSS statement that starts every media query. "At-rule" is the general CSS name for statements beginning with @. |
| Media type | The broad category of output being targeted, such as screen or print. |
| Media feature | The specific property being tested, such as width, orientation or hover, always written inside parentheses. |
| Breakpoint | The width (or other value) at which your layout changes because a media query starts or stops matching. |
| Mobile-first | A workflow where the base styles target small screens, and media queries add styles for larger screens using min-width. |
| Cascade | The CSS system that decides which rule wins when several rules match the same element. Media queries do not change specificity; they only decide whether the rules are in play at all. |
4. The Syntax of a Media Query
Every media query follows the same shape: the @media keyword, an optional media type, one or more conditions in parentheses, and a block of normal CSS.
@media media-type and (media-feature: value) {
selector {
property: value;
}
}
Reading it piece by piece:
@media tells the browser "the rules inside this block are conditional".
media-type is optional; it names the kind of output, such as screen or print.
and joins the type and the conditions, and can also join several conditions together.
(media-feature: value) is the actual test, and the parentheses are compulsory.
- The curly braces contain completely ordinary CSS, written exactly as you would write it anywhere else.
All of these lines are valid query starts:
@media screen and (min-width: 768px) { }
@media (max-width: 600px) { }
@media print { }
@media (orientation: landscape) { }
When no media type is written, the type defaults to all, so @media (max-width: 600px) applies on any device that matches the width condition. You may also meet media queries outside @media: a stylesheet can be loaded only for printing with <link rel="stylesheet" href="print.css" media="print">. In older code you may see the word only after @media; it was a guard for very old browsers and is unnecessary today, so you can omit it.
5. Media Types: What You Can Target
A media type describes the broad destination of the page. There are only a few, and in practice you will use two of them constantly.
| Media type | What it targets |
all | Every device and output mode. This is the default when no type is written. |
screen | Anything with a screen: phones, tablets, laptops, desktop monitors. |
print | Printing and the browser's print preview. |
speech | Screen readers that read a page aloud. |
The print type is the easiest to see in action, because every browser has a print preview. This block hides navigation and sidebars and forces plain black text when the user prints the page:
@media print {
nav,
.sidebar,
.advertisement {
display: none;
}
body {
color: #000000;
font-size: 12pt;
}
}
6. Media Features: What You Can Test
Media features are the real conditions. There are many, but a small set covers almost all everyday work.
The width family
Width-based features are by far the most used, because responsive layout is mostly about horizontal space.
| Feature | Meaning |
width | The current viewport width. |
min-width | True when the viewport is at least this wide. |
max-width | True when the viewport is at most this wide. |
height, min-height, max-height | The same three ideas for viewport height. |
Newer CSS also allows range syntax, which reads like mathematics. Both of these lines mean the same thing:
/* Classic syntax */
@media (min-width: 768px) { }
/* Range syntax, equivalent */
@media (width >= 768px) { }
Range syntax also lets you express a band between two values in one line:
@media (400px <= width <= 900px) { }
Orientation and resolution
@media (orientation: landscape) {
.hero {
flex-direction: row;
}
}
orientation: portrait is true when the viewport is taller than it is wide, landscape when it is wider than it is tall. This is useful for layouts that only work when there is horizontal room.
Features about the user and their device
Modern media queries can also test user preferences and input devices. Two of the most practical:
/* Respect a dark theme chosen in the operating system */
@media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: #f5f5f5;
}
}
/* Reduce motion for users who request it */
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
Other useful features include hover: hover (the device supports hovering with a mouse) and pointer: coarse (the main input is a finger rather than a precise cursor).
7. How a Media Query Works, Step by Step
- The browser parses your stylesheet and reaches the
@media line.
- It first checks the media type. A normal browsing session is always
screen, so a print query does not match while browsing.
- It evaluates each media feature against the current situation. For width features, that measurement is the viewport width in CSS pixels.
- If every condition joined by
and is true, the block becomes active exactly as if it had been written without the query. If any condition fails, the whole block is ignored.
- The browser keeps the query "armed". Every resize, device rotation or print job re-triggers the evaluation instantly, so styles switch in real time.
- Inside the block, normal cascade rules apply. Media queries do not make selectors more powerful, so when a base rule and a query rule have equal specificity, the one written later in the stylesheet wins.
Trace this query through a resizing session:
@media (max-width: 600px) {
.banner {
display: none;
}
}
- Window at 1200px: condition false,
.banner stays visible.
- You drag down to 700px: condition still false, nothing changes.
- At 600px exactly: condition true,
.banner disappears. Note that max-width: 600px matches at exactly 600px.
- You drag back up to 620px: condition false again,
.banner returns.
8. The Viewport Meta Tag: The Required Partner
There is one HTML line without which media queries misbehave on phones. Mobile browsers historically assumed that pages were designed for a wide desktop canvas of roughly 980 pixels, so they rendered the page on that imaginary wide canvas and then zoomed out to fit it. The result: your phone reports a viewport far wider than its real screen, and a query like (max-width: 600px) never fires, even though the physical screen is narrow.
The fix is the viewport meta tag, placed inside <head> of every responsive page:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
width=device-width makes the viewport equal to the device's real width in CSS pixels, instead of a pretend desktop width.
initial-scale=1.0 starts the page without extra zoom.
| Situation | Effect on media queries |
| Viewport meta tag missing | Phone pretends the viewport is very wide; width-based queries fire at the wrong points or never. |
| Viewport meta tag present | Phone reports its true width; your breakpoints behave exactly as designed. |
Whenever a media query "does not work on mobile", the first thing to check is this tag.
9. Worked Example: Your First Media Query
This complete page is small enough to run as it is. Save it as an HTML file, open it, and drag the window narrower than 600 pixels.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Media Query</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 18px;
background-color: #ffffff;
color: #222222;
}
@media (max-width: 600px) {
body {
font-size: 16px;
background-color: #fff8e1;
}
}
</style>
</head>
<body>
<h1>Media Queries Demo</h1>
<p>Drag the window narrower than 600px and watch the page change.</p>
</body>
</html>
What you will observe:
- Above 600px: white background, 18px text.
- At 600px and below: the background becomes pale yellow and the text drops to 16px, because the
max-width query matches and its rules override the base rules (they come later in the stylesheet).
- Dragging back above 600px reverses the change immediately.
10. Min-Width vs Max-Width and Mobile-First Thinking
The direction of your query decides the whole shape of your stylesheet, so this choice deserves a clear head.
| Approach | Base styles describe | Query used | Reads as |
| Desktop-first | The large-screen layout | max-width | "Apply these extra rules up to this width." |
| Mobile-first | The small-screen layout | min-width | "Apply these extra rules from this width upward." |
Both approaches can produce identical pages. The mobile-first approach is preferred in modern work for a simple structural reason: the base styles are the simplest case, and each media query adds complexity for larger screens instead of undoing the work of earlier rules. Phones remain a primary way people browse, so designing from the small screen outward keeps the most constrained case in charge.
Here is the same three-step card grid written both ways.
Desktop-first (base is wide, queries narrow it):
.cards {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
@media (max-width: 900px) {
.cards {
grid-template-columns: 1fr 1fr;
}
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
}
Mobile-first (base is narrow, queries widen it):
.cards {
display: grid;
grid-template-columns: 1fr;
}
@media (min-width: 600px) {
.cards {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 900px) {
.cards {
grid-template-columns: 1fr 1fr 1fr;
}
}
With min-width queries, always write them from smallest to largest breakpoint. Because all matching query rules share the same specificity, the later one wins, and you want the widest layout declared last so it can override narrower ones at large sizes.
11. Combining Conditions
Real conditions are rarely one test. Media queries can be combined with keywords, and the meaning of each keyword is worth memorising.
and: every condition must be true
/* Wide AND horizontal: only laptops and large tablets turned sideways */
@media (min-width: 700px) and (orientation: landscape) {
.hero {
flex-direction: row;
}
}
Comma (or): any one condition is enough
/* Hide the widget when printing OR on very narrow screens */
@media print, (max-width: 500px) {
.widget {
display: none;
}
}
A comma-separated list matches if any single item in it matches. Modern CSS also allows the keyword or between feature conditions, for example (max-width: 500px) or (orientation: portrait), which behaves the same way as the comma version for feature tests.
not: everything except
/* Apply on anything except print */
@media not print {
.animation-area {
animation: pulse 2s infinite;
}
}
not negates the entire query that follows it, so it is usually clearest with a simple query. A very common combination is and chaining a width with a feature, such as @media (min-width: 900px) and (hover: hover) to enable hover effects only on wide, mouse-driven screens.
12. Choosing Breakpoints: Content, Not Devices
Beginners often ask which pixel values are "correct". The honest answer is that breakpoints belong to your content, not to a list of devices. The reliable workflow is:
- Style the page for a narrow screen first.
- Slowly widen the browser window and watch the design.
- The moment the layout starts to look stretched, crowded or awkward, that is a natural breakpoint: add a
min-width query there and fix the layout.
- Keep widening and repeat until the largest size looks good.
As starting points, many teams use values near 600px, 900px and 1200px, and these are sensible first guesses:
| Approximate breakpoint | Typical layout change |
| Around 600px | Single column becomes two columns; horizontal navigation appears. |
| Around 900px | Two columns become three, or a sidebar joins the main content. |
| Around 1200px | Content is centred with a maximum width; extra space becomes padding. |
Two cautions: avoid writing a media query for every device model you have heard of, because devices change constantly and the list is never finished; and prefer two or three well-chosen breakpoints over many tiny ones, because every breakpoint is more CSS to test and maintain.
13. Realistic Worked Example: Responsive Card Page
This final example ties everything together: mobile-first base styles, a horizontal navigation bar that appears on wider screens, a card grid growing from one to three columns, and a dark theme that follows the user's system preference. It is a complete, runnable page.
The complete code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Cards</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
color: #222222;
background-color: #f5f7fa;
}
/* Base styles: mobile first */
.topbar {
display: flex;
flex-direction: column;
gap: 10px;
padding: 16px;
background-color: #1f2937;
}
.topbar a {
color: #ffffff;
text-decoration: none;
}
.container {
max-width: 1100px;
margin: 0 auto;
padding: 16px;
}
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
.card {
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 16px;
}
.card h3 {
margin-top: 0;
}
/* From 640px upward */
@media (min-width: 640px) {
.topbar {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.cards {
grid-template-columns: 1fr 1fr;
}
}
/* From 960px upward */
@media (min-width: 960px) {
.cards {
grid-template-columns: 1fr 1fr 1fr;
}
.card {
padding: 24px;
}
}
/* Dark mode, declared last so it can override the light theme */
@media (prefers-color-scheme: dark) {
body {
background-color: #111827;
color: #e5e7eb;
}
.card {
background-color: #1f2937;
border-color: #374151;
}
}
</style>
</head>
<body>
<header class="topbar">
<strong>My Notes</strong>
<nav>
<a href="#html">HTML</a>
<a href="#css">CSS</a>
<a href="#js">JavaScript</a>
</nav>
</header>
<main class="container">
<div class="cards">
<article class="card">
<h3>HTML Basics</h3>
<p>Structure a web page with semantic tags.</p>
</article>
<article class="card">
<h3>CSS Styling</h3>
<p>Control colour, spacing and layout.</p>
</article>
<article class="card">
<h3>JavaScript</h3>
<p>Add behaviour and interactivity.</p>
</article>
</div>
</main>
</body>
</html>
What happens at each width
- Below 640px: the header stacks its title above the links, and the three cards sit in one column. This is the base stylesheet doing all the work.
- From 640px to 959px: the first query turns the header into a horizontal bar with space between the title and links, and the cards form two columns.
- From 960px upward: the second query widens the grid to three columns and gives each card more breathing room. The container also stops growing past 1100px and centres itself.
- Any width, if the operating system requests a dark theme: the last query recolours the page. It is declared last on purpose, so with equal specificity its rules win over the light theme above.
Notice how little CSS each media query contains. Each one changes only what genuinely needs to change at that size, which is exactly the habit that keeps real stylesheets maintainable.
14. Real-World Patterns You Will Use Again and Again
Beyond changing column counts, media queries solve several everyday problems elegantly. These patterns appear in almost every professional stylesheet, and interviewers like them because they show you think about real users.
Dark mode that follows the operating system
Operating systems let users choose a light or dark appearance, and the prefers-color-scheme feature lets your page honour that choice. The cleanest implementation stores colours in CSS custom properties and swaps them inside one query:
:root {
--page-bg: #ffffff;
--page-text: #1f2937;
--card-bg: #f3f4f6;
}
@media (prefers-color-scheme: dark) {
:root {
--page-bg: #111827;
--page-text: #e5e7eb;
--card-bg: #1f2937;
}
}
body {
background-color: var(--page-bg);
color: var(--page-text);
}
.card {
background-color: var(--card-bg);
}
The components never mention dark colours directly. One small query re-themes the entire page by changing the variables, which is far easier to maintain than writing dark colours in dozens of places.
Hover effects only where hovering exists
Touch screens have no hover, and a tap can leave a :hover style stuck after the finger lifts. Guarding hover styles keeps touch devices clean:
.button {
background-color: #2563eb;
}
@media (hover: hover) and (pointer: fine) {
.button:hover {
background-color: #1d4ed8;
}
}
Respecting reduced motion
Users can ask their operating system for less animation. A short query lets your page cooperate:
@media (prefers-reduced-motion: reduce) {
.banner {
animation: none;
}
.card {
transition: none;
}
}
Notice that none of these patterns involves width at all. Media queries are a general "match the situation" tool, and width is only the most common situation.
15. Media Queries Inside a React Project
Nothing about media queries changes when you move from plain HTML to React. A React component renders real HTML, and its styles live in ordinary CSS files, so the same @media blocks work unchanged. The typical arrangement is one CSS file per component, imported next to the component:
/* Button.css */
.btn {
display: block;
width: 100%;
padding: 12px 20px;
}
@media (min-width: 640px) {
.btn {
display: inline-block;
width: auto;
}
}
import "./Button.css";
function Button({ children }) {
return <button className="btn">{children}</button>;
}
export default Button;
On a phone the button stretches across the screen for easy tapping; from 640px upward it shrinks to fit its text. Two habits worth forming early:
- Inline style objects cannot hold media queries. A React
style prop is a flat set of property values with no room for a conditional block, so responsive rules belong in CSS files, not in style={{ ... }}.
- You rarely need JavaScript to respond to resizing. Beginners often reach for a window resize listener; if the change is purely visual, a media query does it with no code and no re-renders. Use JavaScript only when behaviour itself must change, not just appearance.
16. Common Mistakes and How to Fix Them
Forgetting the viewport meta tag
Symptom: your queries work when you resize a desktop browser but never trigger on a real phone. Cause: the phone pretends the viewport is a wide desktop canvas. Fix: include the tag from part 1 in every page's <head>:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Fixed widths that cannot shrink
A container locked to a large fixed width overflows small screens and forces horizontal scrolling:
/* Wrong: overflows on phones */
.container {
width: 1000px;
}
/* Right: fills small screens, stops growing at 1000px */
.container {
width: 100%;
max-width: 1000px;
margin: 0 auto;
padding: 0 16px;
}
Media queries work best together with fluid layout. Let content stretch and shrink naturally first, and use queries only for structural changes that fluid sizing cannot handle, such as changing the number of columns.
Media queries written before the base styles
When a base rule and a query rule have equal specificity, the later one wins. If the query comes first, the base rule overrides it and the query appears dead:
/* Wrong order: the base rule wins at every width */
@media (min-width: 900px) {
.cards { grid-template-columns: 1fr 1fr 1fr; }
}
.cards { display: grid; grid-template-columns: 1fr; }
Fix: always write base styles first, then your min-width queries from smallest breakpoint to largest. At 1000px both rules above would match, and with the correct order the three-column rule, being later, wins.
Mixing min-width and max-width in one stylesheet
If some queries use min-width and others use max-width, ranges overlap and the cascade becomes a puzzle. Pick one direction, preferably mobile-first with min-width, and stay consistent across the whole project.
A breakpoint for every device model
Writing a query for each phone or tablet you have heard of produces endless fragile CSS. Devices change constantly; your content does not. Fix: two or three content-driven breakpoints, chosen by watching where your own layout breaks as the window widens.
17. Best Practices for Media Queries
- Design mobile-first: base styles for small screens,
min-width queries adding complexity upward.
- Keep each query small: change only what genuinely needs to change at that size.
- Choose breakpoints from your content, not from a device list, and use as few as the design allows.
- Order
min-width queries from smallest to largest so later, wider rules can override earlier ones.
- Build fluid layouts with percentages,
max-width and flexible grid tracks, and reserve media queries for structural changes.
- Guard hover effects with
(hover: hover) so touch devices are not affected.
- Honour
prefers-color-scheme and prefers-reduced-motion; both are one-query wins for user experience.
- Always include the viewport meta tag, and test in the browser's device toolbar plus at least one real phone.
- Comment the purpose of each breakpoint in the stylesheet so teammates understand the intent.
18. Practical Project: A Responsive Landing Page
This project uses everything from both parts: mobile-first base styles, two breakpoints, a navigation bar that reorganises itself, and a fluid hero. Build it in two files in the same folder.
Step 1: Create the HTML
Save this as index.html. Note the viewport meta tag in the head:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SwiftNotes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="site-header">
<p class="logo">SwiftNotes</p>
<nav class="main-nav">
<a href="#features">Features</a>
<a href="#pricing">Pricing</a>
<a href="#contact">Contact</a>
</nav>
</header>
<main>
<section class="hero">
<h1>Notes that follow you everywhere</h1>
<p>SwiftNotes keeps your ideas in one place, on every device.</p>
<a class="cta" href="#signup">Get started free</a>
</section>
<section id="features" class="features">
<article class="feature">
<h2>Fast capture</h2>
<p>Write a note in seconds, from any screen.</p>
</article>
<article class="feature">
<h2>Instant sync</h2>
<p>Notes update across devices automatically.</p>
</article>
<article class="feature">
<h2>Simple search</h2>
<p>Find any note with one search box.</p>
</article>
</section>
</main>
<footer class="site-footer">
<p>© SwiftNotes. All rights reserved.</p>
</footer>
</body>
</html>
Step 2: Write the mobile-first base styles
Save this as style.css. Everything here targets a narrow screen first:
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
color: #1f2937;
background-color: #ffffff;
}
.site-header {
display: flex;
flex-direction: column;
gap: 8px;
padding: 16px;
background-color: #111827;
}
.logo {
margin: 0;
color: #ffffff;
font-weight: bold;
}
.main-nav {
display: flex;
flex-direction: column;
gap: 8px;
}
.main-nav a {
color: #d1d5db;
text-decoration: none;
}
.hero {
padding: 32px 16px;
text-align: center;
}
.hero h1 {
font-size: 28px;
margin: 0 0 12px;
}
.cta {
display: inline-block;
margin-top: 8px;
padding: 12px 24px;
background-color: #2563eb;
color: #ffffff;
text-decoration: none;
border-radius: 6px;
}
.features {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
padding: 16px;
}
.feature {
border: 1px solid #e5e7eb;
border-radius: 8px;
padding: 16px;
}
.site-footer {
padding: 16px;
text-align: center;
background-color: #f3f4f6;
}
Step 3: Add the two breakpoints
Append these queries at the end of style.css, smallest first:
@media (min-width: 640px) {
.site-header {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.main-nav {
flex-direction: row;
gap: 24px;
}
.hero h1 {
font-size: 36px;
}
.features {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 960px) {
.hero {
padding: 64px 16px;
}
.features {
grid-template-columns: repeat(3, 1fr);
padding: 16px 48px;
}
.feature {
padding: 24px;
}
}
Step 4: Test at every width
- Open
index.html in a browser and narrow the window: the nav stacks vertically and the three features sit in one column.
- Widen past 640px: the header becomes a horizontal bar with the logo left and links right, and the features form two columns.
- Widen past 960px: the hero gains breathing room and the features form three columns.
- Open the browser developer tools, enable the device toolbar, and confirm the same behaviour in a phone-sized viewport.
You have now built a complete responsive page with exactly two media queries, which is the level of restraint real projects aim for.
19. Practice Exercises
- Build a page with a paragraph whose font size is 16px below 500px and 20px from 500px upward, using a mobile-first
min-width query.
- Take the card page from part 1 and add a fourth breakpoint that gives the cards a wider gap and larger headings on very wide screens.
- Write a single media query that matches only when the viewport is at least 700px wide and in landscape orientation, and use it to place two boxes side by side with Flexbox.
- Create a print stylesheet for any page you have built: hide the navigation and footer, and set the body text to a serif font under
@media print. Check the result in print preview.
- Add
prefers-color-scheme support to the landing page project using CSS custom properties, then toggle your operating system's theme to verify it.
- Convert a desktop-first stylesheet that uses three
max-width queries into an equivalent mobile-first stylesheet with min-width queries, and confirm the rendered result is identical at 400px, 800px and 1200px.
20. Interview Questions and Answers
What is a media query, and when does the CSS inside it apply?
A media query is a conditional block that starts with @media and wraps ordinary CSS rules. The rules apply only when the stated conditions about the device or viewport are true, such as a minimum width or a colour-scheme preference. The browser re-evaluates the conditions live, so styles switch automatically when the window is resized or a phone is rotated.
What is the difference between min-width and max-width?
min-width: 600px matches when the viewport is 600px wide or wider, so it is used to add styles as screens get bigger, which suits mobile-first development. max-width: 600px matches when the viewport is 600px wide or narrower, so it is used to add styles as screens get smaller, which suits desktop-first development. Both values are inclusive: exactly 600px matches both.
What is mobile-first design and why is it commonly recommended?
Mobile-first means writing the base stylesheet for the smallest screen and then using min-width media queries to enhance the layout for larger screens. It is recommended because the base styles cover the most constrained case, each query adds complexity instead of undoing earlier rules, and the cascade stays predictable because queries are written smallest to largest.
What does the viewport meta tag do and why is it required for media queries?
<meta name="viewport" content="width=device-width, initial-scale=1.0"> tells mobile browsers to size the viewport to the device's real width instead of a pretend desktop canvas of roughly 980 pixels. Without it, width-based media queries evaluate against the fake wide viewport and fire at the wrong points or never fire, even though the physical screen is narrow.
What is a breakpoint and how should you choose breakpoint values?
A breakpoint is the width at which a media query starts or stops matching and the layout changes. Values should be chosen by designing the small-screen layout, widening the window, and adding a query wherever the content starts to look stretched or crowded. Generic values near 600px, 900px and 1200px are common starting points, but the content decides, not a list of device models.
How do you combine multiple conditions in one media query?
Use and when every condition must be true, for example @media (min-width: 700px) and (orientation: landscape). Use a comma, or the or keyword between feature conditions, when any one condition is enough, for example @media print, (max-width: 500px). The not keyword negates a whole query, as in @media not print.
Do media queries increase the specificity of the rules inside them?
No. Rules inside a media query keep the same specificity they would have outside it. When a base rule and a query rule target the same element with equal specificity, the one written later in the stylesheet wins, which is why query order matters so much.
Name some media features other than width.
orientation for portrait versus landscape, prefers-color-scheme for light or dark system themes, prefers-reduced-motion for users who want less animation, hover and pointer to detect mouse-like input, and height with its min- and max- variants. Media types such as print and speech are related tools for non-screen output.
How would you provide different styles for printing?
Use the print media type: @media print { ... } in the stylesheet, or load a separate file with <link rel="stylesheet" href="print.css" media="print">. Typical print rules hide navigation and advertisements, remove background colours, and set body text in points for paper.
Two media queries match the same element with conflicting declarations. What happens?
Both blocks are active, and the normal cascade decides: if specificities are equal, the declaration from the query written later in the stylesheet wins. This is why mobile-first stylesheets list min-width queries in ascending order, so the widest layout overrides narrower ones on large screens.
How do media queries fit into a React application?
React components render normal HTML, so media queries are written in the component's CSS file exactly as in plain HTML, with the component applying class names. Inline style objects cannot contain media queries, so responsive rules must live in CSS files or CSS modules. Purely visual responsiveness should be handled by CSS alone; JavaScript resize handling is reserved for cases where behaviour, not just appearance, must change.
What is the difference between a media type and a media feature?
A media type names the broad category of output, such as screen, print or speech, and is written without parentheses. A media feature tests a specific property of the device or viewport, such as (min-width: 600px) or (orientation: landscape), and is always written inside parentheses. A query can use a type alone, features alone, or both joined with and.
21. Quick Revision Checklist
- A media query is a conditional wrapper:
@media, optional media type, conditions in parentheses, ordinary CSS inside.
min-width means "this width and wider" (mobile-first); max-width means "this width and narrower" (desktop-first).
- The viewport meta tag with
width=device-width is mandatory for phone behaviour.
- Write base styles first, then
min-width queries from smallest to largest breakpoint.
- Media queries add no specificity; later rules win at equal specificity.
- Combine conditions with
and (all must match), commas or or (any may match), and not (negation).
- Choose two or three content-driven breakpoints; never one per device model.
- Know the non-width features:
orientation, prefers-color-scheme, prefers-reduced-motion, hover, pointer.
- Use
@media print for printer-friendly output.
- In React, media queries live in CSS files; inline styles cannot hold them.
22. Official Documentation and Further Reading
Conclusion
Media queries turn a static stylesheet into an adaptive one. With one HTML document, the viewport meta tag, a mobile-first base layer and a handful of well-chosen min-width queries, the same page serves a phone in one hand and a widescreen monitor on a desk, and can even follow the user's dark-mode preference or produce clean printouts. The discipline to remember is restraint: build fluid layouts that need fewer queries, place each breakpoint where your content demands it, and keep every query small. These are exactly the habits you will carry into styling React components, where the same @media blocks continue to do the responsive work no matter how dynamic the JavaScript above them becomes.
Learn more in the React JS Training course, or register for a course demo.