Responsive Design with Media Queries
💻 CSSMake layouts adapt to phones, tablets and desktops with flexible units and breakpoints.
A responsive site looks right on every screen. It uses flexible layouts and a few well-chosen breakpoints instead of separate sites.
- Use relative units.
- Write mobile-first media queries.
- Make images and text scale.
Start Mobile First
Write the small-screen styles first, then add rules for wider screens with min-width. This keeps the base CSS simple and avoids undoing desktop styles.
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
@media (min-width: 640px) {
.cards { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 1024px) {
.cards { grid-template-columns: repeat(3, 1fr); }
}Flexible Units
Use rem for spacing and font sizes, % or fr for widths, and max-width for containers. Avoid fixed pixel widths on major layout blocks.
Images and Text
Set max-width: 100% and height: auto on images. Keep body text at a comfortable size, usually 16px or more, and avoid long lines beyond about 75 characters.
img {
max-width: 100%;
height: auto;
display: block;
}
.prose {
max-width: 65ch;
line-height: 1.7;
}Test with Real Content
Resize the browser slowly and watch for overflow, overlapping text and tiny tap targets. Test with long words, long headings and a slow connection.
Practice
- Turn a three-column layout into one column below 640px.
- Set images to scale inside their container.
- Check tap targets are at least 44px tall.
Hands-on exercise
Write CSS so that .cards shows:
1. One column below 640px.
2. Two columns from 640px.
3. Three columns from 1024px.
Use a 16px gap at every size.
Recap
Responsive design starts with mobile styles and adds breakpoints. Flexible units, fluid images and readable text do most of the work.
Example
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
@media (min-width: 640px) {
.cards { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 1024px) {
.cards { grid-template-columns: repeat(3, 1fr); }
}
Exercises
1. One column below 640px.
2. Two columns from 640px.
3. Three columns from 1024px.
Use a 16px gap at every size.
Expected Output
The grid gains columns as the viewport widens.
Lesson Nav
CSS Course
0/9 lessons completed
- 1 How to Add CSS to HTML Tutorial
- 2 Colors, Fonts, and Text Tutorial
- 3 The Box Model Tutorial
- 4 Flexbox Layout Tutorial
- 5 Build a Landing Page Project
- 6 CSS Grid Layout Tutorial
- 7 Responsive Design with Media Queries Tutorial
- 8 Transitions, Transforms and Animation Tutorial
- 9 Project: A Responsive Portfolio Project