CSSintermediate 9 min
Make layouts adapt to phones, tablets and desktops using media queries and flexible units.
How to use media queries, flexible widths and the viewport meta tag so one page works on every screen size.
More than half of web traffic is on phones. A page that only works on a big monitor loses most of its visitors.
Responsive design means a page adjusts itself to the space available.
Three ingredients:
<meta name="viewport" content="width=device-width, initial-scale=1">, so phones do not zoom out.fr, max-width and rem rather than fixed pixel widths. img { max-width: 100%; } stops images overflowing.This says: "when the window is 500px wide or narrower, use a single column."
A popular approach is mobile first: write the small-screen styles first, then add min-width queries to enhance for larger screens.
@media (max-width: 600px) block applies only when the viewport is 600px wide or less.Change the breakpoint from 600px to 200px and see the layout switch back to three columns.
Next: smooth changes with transitions.
@media (max-width: 500px) {
.grid { grid-template-columns: 1fr; }
}<style>
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.card {
background: #e0e7ff;
padding: 16px;
border-radius: 8px;
text-align: center;
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
.card {
background: #fde68a;
}
}
</style>
<div class="cards">
<div class="card">One</div>
<div class="card">Two</div>
<div class="card">Three</div>
</div>