You open the page you built on a phone, and the cards you’d lined up side by side are crushed together—struggling with phone support is a road everyone walks in web-making. Screen widths differ wildly across computers, tablets, and phones. That’s why there’s a mechanism to switch your CSS to match the screen width. It’s the media query.
Let’s write one
@media (max-width: 600px) {
h1 {
font-size: 24px;
}
}| Part | Meaning |
|---|---|
@media | The signal for “switch depending on the screen” |
(max-width: 600px) | Condition: when the screen width is 600px or less |
Inside { } | CSS that only works when the condition matches |
Read out loud: “if the screen width is 600px or less, make the h1 text 24px.” On a wide screen the normal CSS applies, and the moment it drops to phone size, the rules inside here override.
The most common use: turning a row into a stack
The most common time to reach for a media query is switching between a row on wide screens and a stack on phones. You combine it with Flexbox.
.cards {
display: flex;
gap: 16px;
}
@media (max-width: 500px) {
.cards {
flex-direction: column;
}
}Normally display: flex lays them in a row. Once the width drops to 500px or less, flex-direction: column re-lays them vertically—a single line of override makes it readable on phones too.
Let’s see it in motion
The prerequisite for it to work: viewport
For a media query to work correctly, the HTML side needs an instruction saying “on a phone, display at the actual screen width.” That’s the viewport meta tag written in the head. Without it, the phone shrinks the whole page, and your hard-earned media query never fires.
You can combine two boundaries into a range
Joining min-width and max-width with and lets you write a media query that only works within a range of “at least X and at most Y.”
@media (min-width: 501px) and (max-width: 900px) {
.cards {
flex-direction: column;
}
}This means “only when the width is between 501px and 900px,” used when you want separate CSS for phones, tablets, and computers.
Summary of this lesson
- With
@media (max-width: 600px) { … }, you can write CSS that only works when the screen width matches the condition - The most common use is switching a row (flex) into a stack (column) on phones
- As a prerequisite, the HTML head needs the
viewportmeta tag