Responsive Design
What is Responsive Design?
Responsive design means building a page that adapts to the size of the screen it's viewed on — a phone, a tablet, a laptop, a large desktop monitor. Instead of building separate "mobile" and "desktop" sites, one set of HTML and CSS reflows itself using flexible layouts, flexible images, and media queries.
The Viewport Meta Tag
Before any responsive CSS will work correctly on a phone, this tag must be in the HTML
<head>:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Without it, mobile browsers render the page at a fake desktop-sized width (usually 980px) and then zoom out — which makes your media queries useless, since the browser never reports the real screen width.
Media Queries
Media queries apply CSS only when certain conditions are true — most commonly, screen width:
/* Base styles — written mobile-first, apply to all screens */
.card {
width: 100%;
padding: 12px;
}
/* Tablets and up */
@media (min-width: 768px) {
.card {
width: 50%;
padding: 20px;
}
}
/* Desktops and up */
@media (min-width: 1024px) {
.card {
width: 33.33%;
}
}
Mobile-first vs desktop-first: writing base styles for the smallest screen and
then using min-width to add complexity for bigger screens (as above) is the modern
recommended approach — it keeps mobile devices from downloading and overriding unnecessary
desktop styles.
You can also target a range, or things other than width:
/* Only between 768px and 1023px */
@media (min-width: 768px) and (max-width: 1023px) {
.sidebar { display: none; }
}
/* Portrait vs landscape */
@media (orientation: landscape) { }
/* Respect the user's OS dark mode setting */
@media (prefers-color-scheme: dark) {
body { background: #111; color: #eee; }
}
/* Respect reduced-motion accessibility setting */
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
}
Responsive Images
img {
max-width: 100%; /* never overflow its container */
height: auto; /* keep aspect ratio */
display: block;
}
.hero-bg {
background-image: url("photo-small.jpg");
}
@media (min-width: 1024px) {
.hero-bg {
background-image: url("photo-large.jpg"); /* swap in a bigger image for bigger screens */
}
}
For serving genuinely different image files based on screen size (not just background-image), HTML's
own <picture> element and the srcset attribute give the browser
multiple options to choose from — useful for performance, so phones don't download huge desktop images.