New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› CSS› Responsive Design with Media Queries

Responsive Design with Media Queries

💻 CSS

Make layouts adapt to phones, tablets and desktops with flexible units and breakpoints.

Lesson 7 of 9 Tutorial
0 of 9 completed

A responsive site looks right on every screen. It uses flexible layouts and a few well-chosen breakpoints instead of separate sites.

By the end of this lesson you can:
  • 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.

Warning Do not hide important content on mobile. If it matters on desktop, it matters on a phone.

Practice

  1. Turn a three-column layout into one column below 640px.
  2. Set images to scale inside their container.
  3. 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

Exercise 1. One, two, three columns Medium
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.
CSS exercise-1.css
Expected Output
The grid gains columns as the viewport widens.

Lesson Nav

Lesson sections