Share a layout across pages
Write your menu and page frame once, then use them on every page. This is the trick that makes big sites easy.
Tested on Astro 7.4
Both your pages start and end the same way. Typing that on every page gets old fast. Astro lets you write it once.
A piece you reuse is called a component. A component that wraps a whole page is called a layout. You’ll make one of each.
Step 1: Make a menu
Inside src, make a new folder called components. Inside it, make a file called Nav.astro. Paste this in:
<nav>
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/blog/">Blog</a>
</nav>
<style>
nav {
display: flex;
gap: 1rem;
padding-block: 1rem;
}
</style>
That’s a menu with three links, and a little CSS to space them out. The Blog link goes nowhere yet. We’ll build it next lesson.
Styles inside a component only affect that component. So this nav rule can’t change anything else on your site.
Step 2: Make a layout
Inside src, make a folder called layouts. Inside it, make Layout.astro:
---
import Nav from '../components/Nav.astro';
const { title } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{title}</title>
</head>
<body>
<Nav />
<main>
<slot />
</main>
</body>
</html>
Two lines do the magic:
Astro.propsreceives the page title. A prop is a value a page hands to the layout.<slot />marks the spot where each page’s own content goes. A slot is a hole for content.
Step 3: Use the layout on both pages
Replace everything in src/pages/index.astro with this:
---
import Layout from '../layouts/Layout.astro';
const name = 'Sam';
---
<Layout title="Home">
<h1>Hello, I'm {name}</h1>
<p>This is my first website.</p>
</Layout>
And replace everything in src/pages/about.astro with this:
---
import Layout from '../layouts/Layout.astro';
---
<Layout title="About">
<h1>About me</h1>
<p>I'm learning to build websites with Astro.</p>
</Layout>
Save both.

What you just did
Your pages went from 12 lines to 5. Change the menu once, and it changes on every page. Every real website works this way.
Finished lesson 4?
Mark it done to light its star, and we'll take you straight to lesson 5.