HTML Responsive Pages
A responsive page is a page that adjusts its layout to fit the screen that shows it. The same page serves a phone and a wide monitor.
The viewport tag starts the habit
The viewport tag tells a phone browser to match the page width to the screen. The meta-tags lesson introduced this tag.
<meta name="viewport" content="width=device-width, initial-scale=1.0">One photo in two sizes
The picture element offers a small file for narrow screens and a large file for wide ones. The browser picks one file and shows one photo.
<picture>
<source media="(max-width: 600px)" srcset="harbour-small.jpg">
<img src="harbour-large.jpg" alt="A harbour at dawn">
</picture>
<p>One photo, two sizes.</p>A width that bends
This style rule sets the box width to ninety percent of its space. The box narrows and widens with the screen.
<style>.box { width: 90%; }</style>
<div class="box">
<p>A box at ninety percent width.</p>
</div>Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Harbour Town</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>img { max-width: 100%; }</style>
</head>
<body>
<h1>Harbour Town</h1>
<p>Boats leave with the morning tide.</p>
<picture>
<source media="(max-width: 600px)" srcset="harbour-small.jpg">
<img src="harbour-large.jpg" alt="A harbour at dawn">
</picture>
<p>The harbour at dawn.</p>
</body>
</html>Key points
- Responsive page: a page that adjusts its layout to fit the screen
- Responsive design is one habit built from three small parts working together
- Viewport tag: the meta tag that matches the page width to the screen width
- Picture element: the element that offers more than one size of an image
- Fluid width: a width set as a share of the space, not a fixed pixel count
In this example, three parts work together as one habit. The viewport tag matches the page width to the screen. The style rule caps the image at the full width of its space, so the photo never overflows. The picture element offers a small file for narrow screens and a large file for wide ones. The visible text stays the same at every screen size.
Note
Test a page at a narrow width, since most layout faults show there first
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which three parts make up the responsive habit in this lesson?