CSS Intermediate: Layout and Responsive Design
Responsive Design and Media Queries
In this lesson you will
- Explain responsive design and the viewport tag
- Write a media query with min-width
- Build a layout that changes at a breakpoint
Introduction
People read your page on a tiny phone, a tablet, a laptop and a huge monitor. Responsive design means one page that adapts to all of them, instead of separate sites.
The simple explanation
Start with a layout that works on a small screen, then add rules for larger screens.
This is called mobile-first. A small-screen layout is usually simple (one column), so it is the easiest starting point.
Step one: the viewport tag
In your HTML head, always include:
HTML
<meta name="viewport" content="width=device-width, initial-scale=1">Without it, phones pretend to be wide desktop screens and shrink your page.
Step two: flexible sizes
Avoid fixed widths that are bigger than a phone screen. Prefer:
max-widthinstead ofwidth, so a box shrinks on small screens.- Percentages and
frunits. img { max-width: 100%; height: auto; }so images never overflow.
Quick quiz
Which CSS makes an image shrink to fit a narrow screen?
Step three: media queries
A media query applies CSS only when a condition is true, usually about the screen width.
HTML
@media (min-width: 600px) {
/* these rules apply when the screen is at least 600px wide */
}Here is a layout that is one column on small screens and three columns on wider ones:
The result panel responds to its own width. On a wide screen you will see three columns, on a narrow one a single column.
Mobile-first with min-width
Write the small-screen styles first with no query. Then use min-width queries to add changes as space grows. You can also test other features, such as (prefers-color-scheme: dark) for dark mode, or (prefers-reduced-motion: reduce) for people who dislike animation.
Choosing breakpoints
Do not chase specific devices. Add a breakpoint where your layout starts to look bad. Common starting points are around 600px, 900px and 1200px, but your content decides.
Quick quiz
In a mobile-first approach, which media query type do you mostly use?
Try it yourself
Change the breakpoint to 400px, and make the paragraph text bigger on wide screens by adding a font-size rule inside the media query.
Summary
- Add the viewport tag. Use flexible sizes such as
max-widthand percentages. - A media query applies CSS only when a condition holds.
- Go mobile-first: base styles for small screens,
min-widthqueries for larger ones. - Choose breakpoints where the layout needs them.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading