IntermediateLesson 11 of 15
Responsive Design & Media Queries – HTML & CSS
Layouts that adapt to screen width and devices.
Responsive design means: one page that looks good on smartphone, tablet and desktop. Fundamentals: (1) the viewport meta tag <meta name="viewport" content="width=device-width, initial-scale=1"> – without it, smartphones render the page as a shrunken desktop view; (2) fluid sizes (%, rem, fr, max-width); (3) media queries for adjustments at certain widths.
<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
.spalten { display: grid; gap: 10px; } /* mobile first: one column */
.spalten div { background: #cde; padding: 20px; text-align: center; }
@media (min-width: 480px) { .spalten { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 720px) { .spalten { grid-template-columns: repeat(4, 1fr); } }
.anzeige::after { content: "narrow (< 480px)"; }
@media (min-width: 480px) { .anzeige::after { content: "medium (480–719px)"; } }
@media (min-width: 720px) { .anzeige::after { content: "wide (>= 720px)"; } }
</style>
<p>Currently: <strong class="anzeige"></strong></p>
<div class="spalten"><div>1</div><div>2</div><div>3</div><div>4</div></div>Mobile first: write the base styles for small screens first and add larger layouts with min-width queries. This is leaner than the reverse (max-width) and forces you to focus on the essentials. Other useful media features: orientation, prefers-color-scheme, prefers-reduced-motion, hover: hover (pointing device with hover) and print.
<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
img, svg, video { max-width: 100%; height: auto; } /* media scale along */
h1 { font-size: clamp(1.4rem, 1rem + 3vw, 2.6rem); } /* fluid typography */
.wrap { width: min(100% - 2rem, 60rem); margin-inline: auto; } /* max width with margin */
.info { background: #e8f5e9; padding: 1rem; }
@media (hover: hover) { .info:hover { background: #c8e6c9; } }
@media print { .info { background: none; border: 1px solid #000; } }
</style>
<div class="wrap">
<h1>Fluid Heading</h1>
<svg viewBox="0 0 200 60"><rect width="200" height="60" fill="#3178c6"/><text x="100" y="38" fill="#fff" text-anchor="middle" font-size="20">scales along</text></svg>
<p class="info">Box with hover only on devices with a mouse.</p>
</div>WarningNo horizontal scrolling on the smartphone: common causes are fixed
width values in px, wide tables, images without max-width: 100% and 100vw (including the scrollbar!). Always test in the DevTools device mode and on a real phone, too.TipSet breakpoints where your content breaks, not at "iPhone sizes". For images at different resolutions there are
<img srcset sizes> and <picture>; loading="lazy" loads images only when scrolling.