CPCODELAB
CSS

Media Queries and Responsive Design

11 min read

Adapting Layouts to Any Screen

Media queries apply CSS rules only when certain conditions are true — typically the viewport width. They are the foundation of responsive web design, letting you serve one HTML document with different layouts for mobile, tablet, and desktop.

css
/* Mobile-first approach — base styles target small screens */
.grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

/* 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);
  }
}

/* Wide screen */
@media (min-width: 1280px) {
  .container {
    max-width: 1200px;
    margin: 0 auto;
  }
}

Other Media Features

css
/* Orientation */
@media (orientation: landscape) {
  .hero { min-height: 60vh; }
}

/* Print styles */
@media print {
  .nav, .footer, .sidebar { display: none; }
  body { font-size: 12pt; color: black; }
}

/* High-DPI (retina) displays */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .logo {
    background-image: url("/images/logo@2x.png");
    background-size: 120px auto;
  }
}

Design mobile-first: write your base styles for the smallest screen and use min-width queries to add complexity for larger screens. This ensures a solid foundation on slow mobile connections.

Ready to test yourself?
Practice CSS— quiz & coding exercises