Layouts
Layouts are Astro components used to provide a reusable UI structure, such as a page template.
We conventionally use the term “layout” for Astro components that provide common UI elements shared across pages such as headers, navigation bars, and footers. A typical Astro layout component provides Astro, Markdown or MDX pages with:
- a page shell (
<html>
,<head>
and<body>
tags) - a
<slot />
to specify where individual page content should be injected.
But, there is nothing special about a layout component! They can accept props and import and use other components like any other Astro component. They can include UI frameworks components and client-side scripts. They do not even have to provide a full page shell, and can instead be used as partial UI templates.
However, if a layout component does contain a page shell, its <html>
element must be the parent of all other elements in the component. All <style>
or <script>
elements must be enclosed by the <html>
tags.
Layout components are commonly placed in a src/layouts
directory in your project for organization, but this is not a requirement; you can choose to place them anywhere in your project. You can even colocate layout components alongside your pages by prefixing the layout names with _
.
Sample Layout
Section titled Sample Layout---import BaseHead from '../components/BaseHead.astro';import Footer from '../components/Footer.astro';const { title } = Astro.props;---<html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <BaseHead title={title}/> </head> <body> <nav> <a href="#">Home</a> <a href="#">Posts</a> <a href="#">Contact</a> </nav> <h1>{title}</h1> <article> <slot /> <!-- your content is injected here --> </article> <Footer /> </body> <style> h1 { font-size: 2rem; } </style></html>