Sub topic 3
Laying Out the Page with Grid and Flexbox
Assume you know basic HTML and CSS, can open a page in a browser, and can use developer tools.
Grid and flexbox
Use CSS Grid for the page’s large regions. Give the header and footer their natural height, and let main fill the remaining space. Use Flexbox for items arranged in one direction, such as a logo and navigation links.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Acme Bakery</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
nav ul {
display: flex;
gap: 1.5rem;
list-style: none;
margin: 0;
padding: 0;
}
main { padding: 2rem; }
</style>
</head>
<body>
<header><a href="/">Acme Bakery</a><nav><a href="/menu">Menu</a></nav></header>
<main><h1>Fresh bread every morning</h1></main>
<footer><small>© 2026 Acme Bakery</small></footer>
</body>
</html>Adapting to screen size
Start with a narrow layout. Add columns only when the viewport has enough space. Flexible tracks avoid fixed widths that cause horizontal scrolling.
.hero {
display: grid;
gap: 2rem;
padding: 3rem 1.5rem;
}
@media (min-width: 48rem) {
.hero {
grid-template-columns: 1fr 1fr;
align-items: center;
}
}
.card-grid {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
}Landmarks and skip links
Semantic elements create landmarks: header, nav, main, and footer. Give repeated landmarks distinct accessible names. A skip link lets keyboard users bypass repeated navigation.
Place this as the first focusable element in body:
<a class="skip-link" href="#main">Skip to main content</a>
<main id="main">...</main>Hero images without slowing the page
Set width and height so the browser reserves space before the image loads. Use fetchpriority="high" only for the main above-the-fold image. Write useful alternative text.
<img src="/images/hero-loaf.jpg"
alt="A basket of freshly baked loaves"
width="800" height="600"
fetchpriority="high">Putting the page together
Assemble the structure in reading order: header and navigation, main content with a hero and sections, then footer. Test at narrow and wide widths. Check keyboard focus, heading order, image loading, and horizontal scrolling.
Exercise
Which layout tool should arrange the page regions, and which should arrange links in a row?
Show answer
Use Grid for the page regions and Flexbox for the one-dimensional row of links.