Responsive Design & Mobile First

Difficulty: Intermediate

Question

How do you implement responsive design? What is mobile-first approach?

Answer

Responsive design adapts layouts to different screen sizes. Mobile-first means:

1. Base styles target mobile (smallest screens) 2. Use min-width media queries to add complexity for larger screens 3. Progressive enhancement: start simple, add features

Key techniques: - Fluid layouts with %, vw, fr units - clamp() for fluid typography - Media queries at breakpoints - Responsive images with srcset/picture - Container queries for component-level responsiveness

Code examples

Mobile-First Responsive Layout

/* Base: mobile styles */
.container {
  padding: 1rem;
}
.grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

/* Tablet: 768px+ */
@media (min-width: 768px) {
  .container { padding: 2rem; }
  .grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* Desktop: 1024px+ */
@media (min-width: 1024px) {
  .container {
    max-width: 1200px;
    margin: 0 auto;
  }
  .grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* Fluid typography */
h1 {
  font-size: clamp(1.5rem, 4vw, 3rem);
}

Mobile-first uses min-width queries to progressively enhance. Desktop-first uses max-width to remove features. Mobile-first is the industry standard.

Responsive Images

<!-- srcset: browser picks best image -->
<img
  src="photo-400.jpg"
  srcset="photo-400.jpg 400w,
         photo-800.jpg 800w,
         photo-1200.jpg 1200w"
  sizes="(min-width: 1024px) 33vw,
         (min-width: 768px) 50vw,
         100vw"
  alt="Responsive photo"
/>

<!-- picture: art direction -->
<picture>
  <source media="(min-width: 1024px)"
          srcset="hero-wide.jpg" />
  <source media="(min-width: 768px)"
          srcset="hero-medium.jpg" />
  <img src="hero-mobile.jpg"
       alt="Hero banner" />
</picture>

srcset lets the browser choose the optimal resolution. picture element gives you full art-direction control for different crops at different sizes.

Viewport Meta Tag

<!-- Required in every responsive page -->
<meta name="viewport"
      content="width=device-width, initial-scale=1" />

<!-- Without this, mobile browsers render at
     ~980px width and scale down, making
     media queries useless -->

<style>
/* Common responsive utilities */
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip: rect(0 0 0 0);
}

/* Hide on mobile, show on desktop */
.desktop-only {
  display: none;
}
@media (min-width: 1024px) {
  .desktop-only { display: block; }
}
</style>

The viewport meta tag is essential. Without it, mobile browsers assume a 980px viewport and media queries won't trigger correctly.

Key points

Concepts covered

Media Queries, Mobile First, Viewport, Fluid Typography, Responsive Images