Beginner25 min read

Responsive Design

Learn the fundamentals of responsive web design including relative units, the viewport meta tag, max-width, media queries, and the mobile-first approach to build sites that work on any screen size.

Relative Units

Responsive design means building layouts that adapt to different screen sizes. The first step is to stop relying solely on fixed pixel values and start using relative units.

Common relative units:

UnitRelative to
%Parent element's size
emFont size of the current element
remFont size of the root (<html>) element
vw1% of the viewport width
vh1% of the viewport height
css
.container {
  width: 90%;          /* 90% of the parent's width */
  max-width: 1200px;   /* but never wider than 1200px */
  margin: 0 auto;      /* center horizontally */
}

.text {
  font-size: 1.125rem; /* 18px when root is 16px */
  padding: 1em;        /* padding scales with font size */
}

The max-width property is crucial for responsive design: it lets an element be fluid (using % or vw) while setting an upper limit so content doesn't stretch too wide on large screens.

Media Queries

css
/* Base styles (mobile-first) */
.grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

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

/* Desktop: 1024px and up */
@media (min-width: 1024px) {
  .grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* You can also query other features */
@media (prefers-color-scheme: dark) {
  body {
    background: #0f172a;
    color: #e2e8f0;
  }
}

The Mobile-First Approach

Mobile-first means writing your base CSS for the smallest screens, then adding complexity for larger screens using min-width media queries.

Why mobile-first?

  1. Simpler base styles — Small screens usually need a single-column layout, which is simpler to code.
  2. Progressive enhancement — You add features as screen space increases, rather than removing them for small screens.
  3. Performance — Mobile devices load only the base styles by default; additional rules only apply when the viewport is wide enough.

The viewport meta tag is essential for responsive design. Without it, mobile browsers render pages at a virtual desktop width (typically 980px) and then shrink the result. Add this to your <head>:

html
<meta name="viewport" content="width=device-width, initial-scale=1">

This tells the browser to set the viewport width equal to the device width, giving you a 1:1 pixel relationship and enabling your media queries to work correctly.

In a mobile-first approach, which type of media query should you use to add styles for larger screens?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.