Lesson 21 / 25

Modern CSS features

clamp(), aspect-ratio, gap, and other modern CSS properties that make responsive design simpler and more intuitive.

CSS clamp() for responsive sizing

clamp(min, preferred, max) scales values smoothly without media queries.

/* Padding grows from 1rem to 3rem as viewport scales */
.section { padding: clamp(1rem, 3vw, 3rem); }

/* Font size scales smoothly from 14px to 20px */
body { font-size: clamp(0.875rem, 1.5vw, 1.25rem); }

/* Width scales with min and max */
.container { width: clamp(300px, 90%, 1200px); }

aspect-ratio for media

Preserve image and video aspect ratio automatically, preventing layout shift.

/* Reserve space for image before it loads */
img { aspect-ratio: 16 / 9; width: 100%; object-fit: cover; }

/* Video player */
video { aspect-ratio: 16 / 9; width: 100%; }

gap for consistent spacing

Unified spacing between flex and grid items without margin hacks.

.flex-row {
  display: flex;
  gap: 1rem; /* Space between all items */
  flex-wrap: wrap;
}

.grid {
  display: grid;
  gap: 1.5rem; /* Row and column spacing */
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}

Browser support for modern CSS

clamp(), gap, aspect-ratio are well supported in modern browsers. Check caniuse.com for older features.

Safe fallbacks for modern CSS

Use fallbacks for older browsers that don't support modern features.

/* Fallback for older browsers */
.card { width: 33.333%; float: left; }

/* Modern browsers */
@supports (display: grid) {
  .card { width: auto; float: none; }
  .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); }
}