CSSLesson 10 of 10Jump to practice
Responsive design
Make one page work well on phones, tablets and desktops with flexible sizes and media queries.
More than half of all web traffic comes from phones. A responsive page adapts its layout to whatever screen it’s on, instead of making visitors pinch and zoom.
Three things make a page responsive.
1. The viewport tag
From the HTML course. Without it, phones pretend to be a desktop screen and shrink your page.
<meta name="viewport" content="width=device-width, initial-scale=1">
2. Flexible sizes
Avoid fixed widths like width: 960px. Prefer:
max-widthso things can shrink:max-width: 960px; margin: 0 auto;- percentages and
frunits remfor text- images that never overflow:
img {
max-width: 100%;
height: auto;
}
3. Media queries
A media query applies CSS only when a condition is true, usually a minimum screen width.
/* Phones: one column (the default) */
.columns { display: block; }
/* 600px and wider: two columns */
@media (min-width: 600px) {
.columns {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
The width at which the layout changes is called a breakpoint.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; margin: 10px; }
.columns div { background: #cfeee9; padding: 16px; margin-bottom: 10px; }
@media (min-width: 500px) {
.columns {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.columns div { margin-bottom: 0; }
}
</style>
</head>
<body>
<div class="columns">
<div>On a phone, I'm on top.</div>
<div>On a wider screen, I'm on the right.</div>
</div>
<p id="width"></p>
<script>
function show() {
document.getElementById("width").textContent =
"This area is " + window.innerWidth + "px wide.";
}
show();
window.addEventListener("resize", show);
</script>
</body>
</html>Open it in the editor and resize your window across 500px to watch it switch.
Mobile first
Write your base CSS for small screens, then use min-width media queries to add complexity as the screen grows. Phones download only the simple styles they need, and you rarely have to undo anything.
Common breakpoints are around 600px (large phones and small tablets) and 1000px (laptops). Choose yours by where your layout starts to look wrong, not by specific devices.
Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Apply these styles only when the screen is at least 700px wide.
@media (: 700px) { .columns { display: flex; } }Exercise 2Solved
Stop images from overflowing narrow screens.
img { : 100%; height: auto; }Images can shrink, but they should never grow past their real size.
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.