CSS Responsive Design - johnverz22/webdev1-lessons GitHub Wiki

1. What is Responsive Design?

Responsive design makes your website look good on all devices—phones, tablets, laptops, desktops.


2. Start with the Layout

Use a Fluid Layout

  • Avoid fixed widths.
  • Use percentage-based widths.
.container {
  width: 90%;
  margin: auto;
}

Choose a Layout System

Use Flexbox or CSS Grid for dynamic layouts.

Flexbox Example:

.parent {
  display: flex;
  flex-wrap: wrap;
}

.child {
  flex: 1 1 300px;
}

Grid Example:

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

3. Use Responsive Units

Preferred Units

  • % for widths
  • em or rem for spacing and font sizes
  • vw and vh for full-screen elements
  • Avoid px for layouts

Example:

body {
  font-size: 1rem;
  padding: 2vw;
}

4. Media Queries

Change styles based on screen size.

@media (max-width: 768px) {
  .menu {
    flex-direction: column;
  }
}

Breakpoint Examples

  • max-width: 600px → Phones
  • max-width: 768px → Tablets
  • max-width: 1024px → Small laptops
  • min-width: 1025px → Desktops

5. Images and Media

Make Images Scale

img {
  width: 100%;
  height: auto;
}

Use picture for art direction

<picture>
  <source media="(max-width: 600px)" srcset="small.jpg">
  <img src="large.jpg" alt="responsive image">
</picture>

You're right.

That example uses px, not rem. Here's the corrected version using rem properly:


6. Typography Tips

  • Set the base font size using rem
  • All other font sizes should scale from this base
html {
  font-size: 1rem; /* This equals 16px by default */
}

body {
  font-size: 1rem;    /* 16px */
  line-height: 1.5rem; /* 24px */
}

h1 {
  font-size: 2rem;    /* 32px */
}

Adjust with Media Queries

@media (max-width: 600px) {
  html {
    font-size: 0.875rem; /* Scales everything down to 14px */
  }
}

7. Responsive Navigation

  • Collapse into a hamburger on small screens.
  • Use media queries to toggle display.
.nav {
  display: flex;
}

@media (max-width: 600px) {
  .nav {
    display: none;
  }

  .menu-toggle {
    display: block;
  }
}

8. Viewport Meta Tag

Add this to your HTML <head>:

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

9. Mobile-First Approach

  • Design for small screens first.
  • Add larger breakpoints later.
/* Mobile default */
.card {
  padding: 1rem;
}

/* Tablet and up */
@media (min-width: 768px) {
  .card {
    padding: 2rem;
  }
}

10. Testing Tools

  • Chrome DevTools device toolbar
  • Responsively App
  • Screen size simulator websites

Do you want a sample responsive page to try this out?

⚠️ **GitHub.com Fallback** ⚠️