Topic 14 of 30
Responsive Design
Overview
Responsive design ensures websites look and work well on all screen sizes — mobile, tablet, and desktop. With over 60% of web traffic now on mobile, responsive design is not optional.
Syntax
css
/* Mobile-first approach (recommended) */
/* Base styles — mobile */
.container {
padding: 16px;
font-size: 14px;
}
/* Tablet */
@media (min-width: 768px) {
.container {
padding: 24px;
font-size: 16px;
}
}
/* Desktop */
@media (min-width: 1024px) {
.container {
max-width: 1200px;
margin: 0 auto;
padding: 40px;
}
}Common Pitfalls
- Always add <meta name='viewport' content='width=device-width, initial-scale=1.0'> in <head> for responsive to work.
- Mobile-first (min-width queries) is better than desktop-first (max-width) — it scales up naturally.
- Interview tip: Container queries (@container) let you apply styles based on the parent container size, not the viewport.
Real-World Example
A responsive product grid that stacks on mobile:
example
css
/* Mobile: 1 column */
.products-grid {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
padding: 16px;
}
/* Tablet: 2 columns */
@media (min-width: 640px) {
.products-grid {
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
}
/* Desktop: 4 columns */
@media (min-width: 1024px) {
.products-grid {
grid-template-columns: repeat(4, 1fr);
gap: 24px;
max-width: 1280px;
margin: 0 auto;
}
}
/* Fluid alternative with no media queries */
.auto-grid {
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
}