CSS Responsive Design: Media Queries and Mobile-First
Responsive design is a core front-end skill. Here's what exams test — media queries, mobile-first strategy, and the viewport.
The viewport meta tag
Without this tag, mobile browsers zoom out to fit desktop-sized pages. This tag tells the browser to match the device width.
<!-- Required in every responsive page --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> /* Without this: - Mobile renders at ~980px wide and scales down - Media queries won't trigger as expected With this: - viewport width = device's actual screen width - Media queries work correctly */
Media queries
Media queries apply styles conditionally based on the viewport or device characteristics.
/* Breakpoint examples */
@media (max-width: 768px) {
.sidebar { display: none; }
}
@media (min-width: 768px) and (max-width: 1200px) {
.grid { grid-template-columns: repeat(2, 1fr); }
}
/* Screen vs print */
@media print {
.nav, .sidebar { display: none; }
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
body { background: #0f172a; color: #f8fafc; }
}
/* Pointer (touch vs mouse) */
@media (pointer: coarse) {
button { min-height: 44px; } /* larger touch targets */
}Mobile-first vs desktop-first
Mobile-first starts with styles for small screens, then adds overrides for larger screens. Desktop-first is the opposite.
/* Mobile-first: base styles for small screens */
.card { width: 100%; }
/* Then add styles for larger screens */
@media (min-width: 768px) {
.card { width: 50%; }
}
@media (min-width: 1200px) {
.card { width: 33.33%; }
}
/* Desktop-first: base for large, override for small */
.card { width: 33.33%; }
@media (max-width: 1200px) {
.card { width: 50%; }
}
@media (max-width: 768px) {
.card { width: 100%; }
}Fluid units and relative sizing
Fluid layouts use relative units instead of fixed pixels.
/* Relative units */
font-size: 1rem; /* relative to root font-size */
font-size: 1.5em; /* relative to parent font-size */
width: 80%; /* percentage of parent */
width: 50vw; /* 50% of viewport width */
height: 100vh; /* 100% of viewport height */
/* Fluid font size with clamp() */
font-size: clamp(1rem, 2.5vw, 2rem);
/* minimum: 1rem, preferred: 2.5vw, maximum: 2rem */
/* fluid max-width pattern */
.container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 0 16px;
}Exam tip
The most common responsive design question: "What's mobile-first?" — you write base styles for mobile, then use min-width media queries to add styles for larger screens. It's better because it forces prioritisation and results in less CSS override.
Think you're ready? Prove it.
Take the free HTML & CSS readiness test. Get a score, topic breakdown, and your exact weak areas.
Take the free HTML & CSS test →Free · No sign-up · Instant results