Responsive design: an adaptive menu
| The menu | |
| One grid, three layouts | |
| How it was done before | |
| The viewport tag | |
| Test it |
A responsive (adaptive) page changes its layout with the width of the screen instead of making a phone user scroll sideways. This page shows it on a site menu: four columns on a wide screen, two on a tablet, one on a phone. Make the browser window narrower to watch it change. The tools are CSS grid and media queries.
The menu
One grid, three layouts
The HTML is one list of columns. Each column is a section link with its sub-links:
<nav class="menu-demo"> <div class="col"><a href="/linux/">Linux</a> <ul><li><a href="/linux/debian/">Debian</a></li> … </ul></div> … three more columns … </nav>
The CSS sets four equal columns, and two media queries reduce them to two below 900 pixels and to one below 500:
.menu-demo { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; } @media (max-width: 900px) { .menu-demo { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 500px) { .menu-demo { grid-template-columns: 1fr; } }
1fr is one share of the free space, so the columns stay equal at any width. The browser moves the same four blocks into new rows by itself.
How it was done before
The first version of this page did the same with tables. The menu was in the HTML four times, as four tables with a different number of columns, one per range of screen widths, and media queries hid all but one:
@media screen and (min-width: 1840px) { /* desktop */ .width_a, .width_b, .width_c { display: none; } } @media screen and (max-width: 1839px) and (min-width: 1200px) { /* tablet */ .width_a, .width_b, .width_d { display: none; } }
It worked, but every new link had to be added four times, the page carried four copies of the menu, and tables meant for data told screen readers the menu was a table. A grid keeps one copy and leaves the layout to CSS.
The viewport tag
Media queries work on a phone only if the page has this tag in its head; without it the phone pretends to be about 980 pixels wide and shows the desktop layout, zoomed out:
<meta name="viewport" content="width=device-width, initial-scale=1">
Test it
Open the developer tools (F12) and switch on the device toolbar (Ctrl+Shift+M in Chrome and Firefox), then pick a phone or drag the width. More checks for a site: Website testing.
Article authors: Andrei Olegovich, Klavdiya Kondakova
| Web | |
| CSS test: shapes and line numbers | |
| A tram drawn with CSS | |
| CSS | |
| HTML |