NelsonLabs
CSS Styling/Responsive Design

Responsive Design

Responsive design means your site works correctly on every screen size โ€” from a 4-inch phone to a 34-inch ultrawide monitor. It's not optional: more than half of all web traffic is mobile.

The viewport meta tag โ€” always required

Without this, mobile layouts break
html
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Without this, mobile browsers zoom out to show the desktop layout -->

Media queries

Media queries apply CSS only when a condition is met โ€” typically when the screen is a certain width. This lets you write different styles for different screen sizes.

Media queries
css
/* Mobile-first: write base styles for mobile, then add rules for larger screens */

/* Base styles (mobile) */
.grid {
  display: grid;
  grid-template-columns: 1fr;  /* single column on mobile */
  gap: 1rem;
}

/* Tablet (640px and up) */
@media (min-width: 640px) {
  .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 target max-width (desktop-first approach) */
@media (max-width: 768px) {
  .sidebar { display: none; }
}

/* Target device features */
@media (prefers-color-scheme: dark) { /* user prefers dark mode */ }
@media (prefers-reduced-motion: reduce) { /* user prefers less animation */ }

TIP

Mobile-first is the right approach. Write your base CSS for small screens first, then progressively add styles for larger screens with min-width queries. Mobile-first CSS tends to be cleaner and simpler โ€” you're adding complexity as screens get bigger, not stripping it away.

Responsive images

Images that never overflow their container
css
img {
  max-width: 100%;
  height: auto;
}
/* This one rule prevents images from breaking mobile layouts */