Websites that adapt to different screen sizes:
One website, many devices.
Essential for responsive design:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Without this, mobile browsers assume your site is desktop-only!
/* Base styles (mobile) */ .container { width: 100%; } /* Tablet and up */ @media (min-width: 768px) { .container { width: 750px; } }
@media (condition) { /* Styles that apply when condition is true */ }
Common conditions:
@media (min-width: 768px) { } /* 768px and wider */ @media (max-width: 767px) { } /* 767px and narrower */ @media (orientation: landscape) { }
These are guidelines, not rules. Test on real devices!
/* Mobile first (default) */ .card-grid { display: grid; grid-template-columns: 1fr; gap: 20px; } /* Tablet: 2 columns */ @media (min-width: 576px) { .card-grid { grid-template-columns: repeat(2, 1fr); } } /* Desktop: 3 columns */ @media (min-width: 992px) { .card-grid { grid-template-columns: repeat(3, 1fr); } }
Use percentages and relative units:
.container { width: 90%; /* percentage of parent */ max-width: 1200px; /* but not too wide */ margin: 0 auto; /* center it */ } .sidebar { width: 25%; } .main-content { width: 75%; }
%
em
rem
vw
vh
body { font-size: 16px; } h1 { font-size: 2rem; } /* 32px */ p { font-size: 1rem; } /* 16px */
img { max-width: 100%; /* never wider than container */ height: auto; /* maintain aspect ratio */ }
For different images on different screens:
<picture> <source media="(min-width: 800px)" srcset="large.jpg"> <source media="(min-width: 400px)" srcset="medium.jpg"> <img src="small.jpg" alt="Description"> </picture>
/* Base size */ html { font-size: 16px; } /* Larger on bigger screens */ @media (min-width: 768px) { html { font-size: 18px; } } /* Use rem for all text */ h1 { font-size: 2.5rem; } p { font-size: 1rem; }
/* Hide on mobile */ .desktop-only { display: none; } @media (min-width: 768px) { .desktop-only { display: block; } } /* Hide on desktop */ @media (min-width: 768px) { .mobile-only { display: none; } }
/* Mobile: hamburger menu (hidden by default) */ .nav-links { display: none; } .nav-links.active { display: flex; flex-direction: column; } /* Desktop: always visible, horizontal */ @media (min-width: 768px) { .nav-links { display: flex; flex-direction: row; } .hamburger { display: none; } }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
This creates a responsive grid without media queries!