In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.
How the Guide page is wrapped
MainLayout: header, nav, main, footerwrites @Body inside main; the DefaultLayout for pages without @layoutGuideLayout, marked @layout MainLayoutrendered into MainLayout's @Body; its step links stay on screenGuide page, marked @layout GuideLayoutchain MainLayout > GuideLayout > Guide; Home gets MainLayout onlyEach layout renders the next part where it writes @Body. Scoped CSS from MainLayout.razor.css reaches page elements only through rules like main ::deep h1.
What a layout is
A layout is an ordinary Razor component with one extra rule: it inherits LayoutComponentBase. That base class adds one parameter, Body, of type RenderFragment. A RenderFragment is a piece of UI that has not been rendered yet. When the layout writes @Body, Blazor renders the page at that spot. Everything else in the layout, such as the header, the navigation and the footer, stays on screen while pages change.
The @layout directive compiles into a [Layout(typeof(GuideLayout))] attribute on the component class. RouteView reads that attribute from the page it is about to show. If the page has none, it uses its DefaultLayout parameter. It then renders a LayoutView, which checks whether the chosen layout has a [Layout] attribute of its own and keeps going outward until a layout has none. The result is a chain from the outermost layout to the page, in which each layout's Body holds the next part.
Nested layouts and layout state
Nesting lets one section of an app add its own frame without copying the main one. In LayoutLab, GuideLayout declares @layout MainLayout. A page with @layout GuideLayout is therefore rendered as MainLayout, then GuideLayout inside its Body, then the page inside GuideLayout's Body. Home has no @layout, so it gets DefaultLayout and only MainLayout around it.
Layouts are components, so they can hold state and handle events. After each navigation Blazor compares the new render tree with the old one. When the next page uses the same layout types in the same order, the existing layout instances stay and only their Body changes. That is why GuideLayout's Hide steps choice survives a move from guide/1 to guide/2. When you go to Home, GuideLayout leaves the tree, and the next visit to the guide creates a new instance with the steps shown again.
How CSS isolation works
A file named MainLayout.razor.css next to MainLayout.razor holds styles for that component only. At build time the component gets a scope id: b- followed by ten characters. Every selector in the file is rewritten so that its last part requires an attribute with that name, so header becomes header[b-ecgrkojuna]. The Razor compiler adds the same attribute to every HTML element written in MainLayout.razor. All rewritten files are bundled into one stylesheet named after the assembly, LayoutLab.styles.css, which index.html links. SharpRune performs the same steps on the device. The .NET SDK on a computer can produce a different id, with the same effect.
The consequence is precise. Elements written in other .razor files do not carry MainLayout's attribute, even when they appear inside MainLayout on screen. A page rendered through @Body has its own elements, and a child component such as NavLink renders its own a element. That is why the plain p rule in MainLayout.razor.css gives a dashed border to the footer paragraph and to no paragraph on Home. Components are not elements, so the attribute is never placed on a component tag.
Reaching child content with ::deep
::deep changes where the attribute goes. In nav ::deep a, the attribute moves to the part before ::deep, and the rule becomes nav[b-ecgrkojuna] a. The nav element is written in MainLayout.razor, so it carries the attribute, and every a element inside it matches, including the ones NavLink renders. The same rule shape underlines page headings: main ::deep h1 becomes main[b-ecgrkojuna] h1, and every page is rendered inside that main element.
::deep needs an element of the parent component to anchor the rule. A rule that starts with ::deep, such as ::deep h1, becomes [b-ecgrkojuna] h1, which matches h1 elements inside any element of the component. That is wider than most people intend. It is clearer to wrap child content in a named element, as LayoutLab does with nav and main, and to write the rule against that element.
Trace LayoutLab
App.razor sets DefaultLayout to MainLayout and wraps the NotFound message in a LayoutView with the same layout. Open Home: RouteView finds no [Layout] attribute on Home, uses MainLayout, and MainLayout renders its header, the page inside main and the footer. The h1 on Home has no scope attribute, but main has one, so main ::deep h1 draws the purple line. The three paragraphs on Home have no attribute, so p[b-ecgrkojuna] skips them, while the footer paragraph matches.
Tap Guide. Guide has @layout GuideLayout, and GuideLayout has @layout MainLayout, so the chain is MainLayout, GuideLayout, Guide. MainLayout is the same type as before, so its instance stays. GuideLayout is new and renders the Guide panel and its step links. Its styles live in app.css, which is global and not scoped, so .steps a.active can style NavLink output without ::deep. Tap Hide steps and then Next step: Guide receives a new Step value, GuideLayout stays, and its showSteps field keeps the value false.
Common mistakes
Putting @layout MainLayout in the root _Imports.razor applies it to every component below that folder, including MainLayout itself. The layout then wraps itself without end. Set the default on RouteView with DefaultLayout, or put @layout in an _Imports.razor inside a folder that contains only pages.
A layout without @inherits LayoutComponentBase has no Body parameter, so Blazor throws when it tries to pass the page in. Styling NavLink from a .razor.css file without ::deep has no effect, because the a element comes from the NavLink component. A missing link to the {AssemblyName}.styles.css file in index.html removes every scoped style while global styles keep working, which looks like a broken selector. And a .razor.css file only belongs to the component with the same file name: Home.razor.css does nothing for Guide.razor.
Practice and review
Create a Pages/Docs folder with an _Imports.razor that contains @layout GuideLayout, move Guide.razor into it and remove its own @layout line. The app should look the same. Then add Home.razor.css with an h1 rule that changes the color, and check that the heading on Guide keeps its color. Last, remove ::deep from nav ::deep a.active, run again, and explain why the active link loses its background.
- A layout inherits
LayoutComponentBaseand renders the page where it writes@Body. RouteView'sDefaultLayoutapplies to pages without@layout.@layouton a page or on a layout overrides it and can nest layouts.Layoutinstances stay while the layout chain stays the same, so layout state survives navigation.- A .
razor.cssfile is rewritten to require the component's b- attribute, which only elements in that .razor file carry. - ::deep puts the attribute on the part before it, so a rule reaches pages and child components rendered inside that element.
Layouts and component-scoped CSS — Blazor WebAssembly project
Run the project
- Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
- Compare Home and Guide. The header and the dashed footer stay the same; Guide adds the Guide panel from GuideLayout. Notice which paragraphs have a dashed border.
- On Guide, tap Hide steps, then Next step a few times. The steps stay hidden, because GuideLayout keeps its state.
- Change a .razor file and tap Run again to rebuild.
- On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.
Project files
LayoutLab.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>LayoutLab</AssemblyName>
<RootNamespace>LayoutLab</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
</ItemGroup>
</Project>
Program.cs
Download file ↗using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using LayoutLab;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
App.razor
Download file ↗<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
@* DefaultLayout is used for every page that has no @layout directive. *@
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
@* LayoutView puts content that is not a page into a layout. *@
<LayoutView Layout="@typeof(MainLayout)">
<h1>Not found</h1>
<p>There is no page at this address.</p>
</LayoutView>
</NotFound>
</Router>
_Imports.razor
Download file ↗@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using LayoutLab
@using LayoutLab.Layout
Layout/GuideLayout.razor
Download file ↗@* A nested layout. GuideLayout renders inside MainLayout,
and the page renders inside GuideLayout's @Body. *@
@inherits LayoutComponentBase
@layout MainLayout
<div class="guide">
<div class="guide-bar">
<strong>Guide</strong>
<button class="link" @onclick="() => showSteps = !showSteps">@(showSteps ? "Hide steps" : "Show steps")</button>
</div>
@if (showSteps)
{
<div class="steps">
<NavLink href="guide" Match="NavLinkMatch.All">Overview</NavLink>
<NavLink href="guide/1">Step 1</NavLink>
<NavLink href="guide/2">Step 2</NavLink>
<NavLink href="guide/3">Step 3</NavLink>
</div>
}
<section class="guide-body">
@Body
</section>
</div>
@code {
// A layout is a normal component with state. Moving between guide pages
// keeps this instance, so the hidden or shown steps stay as you left them.
private bool showSteps = true;
}
Layout/MainLayout.razor
Download file ↗@* A layout is a component that inherits LayoutComponentBase.
That base class gives it one parameter, Body: the page to show. *@
@inherits LayoutComponentBase
<div class="shell">
<header>
<a class="brand" href="">Layout Lab</a>
<nav>
<NavLink href="" Match="NavLinkMatch.All">Home</NavLink>
<NavLink href="guide">Guide</NavLink>
</nav>
</header>
<main>
@Body
</main>
<footer>
<p>This footer paragraph is written in MainLayout.razor, so the p rule in MainLayout.razor.css gives it a dashed border.</p>
</footer>
</div>
Layout/MainLayout.razor.css
Download file ↗/* Scoped to MainLayout. The build rewrites every selector here, for example
header becomes header[b-xxxxxxxxxx], and adds that attribute to each
element written in MainLayout.razor. */
.shell {
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
position: sticky;
top: 0;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 16px;
padding: 12px 16px;
background: #1f1b3a;
color: #fff;
}
.brand {
color: #fff;
font-weight: 700;
text-decoration: none;
margin-right: auto;
}
nav {
display: flex;
gap: 4px;
}
/* NavLink is a child component. Its <a> does not get MainLayout's attribute,
so "nav a" would match nothing. ::deep moves the attribute to nav. */
nav ::deep a {
color: #d9d4ff;
text-decoration: none;
padding: 6px 10px;
border-radius: 8px;
}
nav ::deep a.active {
background: #6b4eff;
color: #fff;
}
main {
flex: 1;
width: 100%;
max-width: 720px;
margin: 0 auto;
padding: 20px 16px 24px;
box-sizing: border-box;
}
/* Pages render inside this main element, so ::deep reaches their h1. */
main ::deep h1 {
border-bottom: 3px solid #6b4eff;
padding-bottom: 4px;
}
/* No ::deep: only <p> elements written in MainLayout.razor match. */
p {
margin: 0;
padding: 10px 12px;
border: 2px dashed #6b4eff;
border-radius: 10px;
font-size: 0.9rem;
}
footer {
width: 100%;
max-width: 720px;
margin: 0 auto;
padding: 0 16px 24px;
box-sizing: border-box;
}
Pages/Guide.razor
Download file ↗@page "/guide"
@page "/guide/{Step:int}"
@* This page picks its own layout instead of the default. *@
@layout GuideLayout
<PageTitle>Guide</PageTitle>
<h1>@(Step is null ? "Guide overview" : $"Step {Step}")</h1>
<p class="lead">@Text</p>
<p class="muted">Nesting: MainLayout, then GuideLayout, then Guide.razor.</p>
@if (Step is null or < 3)
{
<a class="next" href="guide/@((Step ?? 0) + 1)">Next step</a>
}
@code {
// Null on /guide, a number on /guide/2.
[Parameter]
public int? Step { get; set; }
private string Text => Step switch
{
null => "This page has @layout GuideLayout. GuideLayout has @layout MainLayout. So the header comes from MainLayout, the Guide bar and steps come from GuideLayout, and this text comes from the page.",
1 => "A layout inherits LayoutComponentBase and writes @Body where the page goes. Tap Hide steps, then move between steps: GuideLayout keeps its state, because the same layout instance stays on screen.",
2 => "RouteView's DefaultLayout applies to pages without @layout. Home uses it. This page overrides it with @layout GuideLayout.",
_ => "Each .razor.css file is scoped to its own component. MainLayout.razor.css draws the line under this heading with main ::deep h1, because the page renders inside MainLayout's main element."
};
}
Pages/Home.razor
Download file ↗@page "/"
<PageTitle>Layout Lab</PageTitle>
<h1>Layout Lab</h1>
<p>This page has no @@layout directive, so RouteView wraps it in its DefaultLayout, MainLayout. The dark header and the dashed footer come from MainLayout.razor. This text is the page itself, placed where MainLayout writes @@Body.</p>
<p>The purple line under the heading comes from MainLayout.razor.css. The rule <code>main ::deep h1</code> reaches into the page.</p>
<p>MainLayout.razor.css also has a plain <code>p</code> rule with a dashed border. This paragraph does not get it, because the rule became <code>p[b-…]</code> and only elements written in MainLayout.razor carry that attribute.</p>
<ul class="cards">
<li><a href="guide"><strong>Guide</strong><span>A page inside a nested layout</span></a></li>
<li><a href="guide/2"><strong>Guide, step 2</strong><span>The same layouts with a route parameter</span></a></li>
</ul>
wwwroot/css/app.css
Download file ↗:root {
color-scheme: light dark;
--accent: #6b4eff;
--line: #d8d6e4;
}
body {
margin: 0;
font-family: -apple-system, system-ui, sans-serif;
line-height: 1.5;
}
a, button, input, label {
touch-action: manipulation;
}
a {
color: var(--accent);
}
h1 {
font-size: 1.7rem;
margin: 0 0 12px;
}
h1:focus {
outline: none;
}
h2 {
font-size: 1.15rem;
margin: 24px 0 8px;
}
code {
font-size: 0.9em;
overflow-wrap: anywhere;
}
.loading {
padding: 32px 16px;
color: #777;
}
.row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin: 12px 0;
}
input:not([type=checkbox]) {
font: inherit;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
min-width: 0;
background: transparent;
color: inherit;
}
button {
font: inherit;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: transparent;
color: inherit;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:disabled {
opacity: 0.45;
}
.muted {
color: #777;
}
#blazor-error-ui {
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
background: #ffe8a3;
color: #222;
}
/* Global styles in app.css apply to every component. They are not scoped. */
button.link {
border: none;
color: var(--accent);
padding: 4px 6px;
}
.cards {
list-style: none;
padding: 0;
display: grid;
gap: 10px;
}
.cards a {
display: flex;
flex-direction: column;
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 12px;
color: inherit;
text-decoration: none;
}
.cards span {
color: #777;
}
.guide {
border: 1px solid var(--line);
border-radius: 14px;
overflow: hidden;
}
.guide-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px;
background: rgba(107, 78, 255, 0.12);
}
.steps {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
}
.steps a {
padding: 4px 10px;
border-radius: 999px;
border: 1px solid var(--line);
text-decoration: none;
}
.steps a.active {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
.guide-body {
padding: 16px 14px;
}
.lead {
font-size: 1.05rem;
}
.next {
display: inline-block;
margin-top: 8px;
padding: 8px 14px;
border-radius: 8px;
background: var(--accent);
color: #fff;
text-decoration: none;
}
wwwroot/index.html
Download file ↗<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Layout Lab</title>
<base href="/" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="LayoutLab.styles.css" />
</head>
<body>
<div id="app">
<p class="loading">Starting .NET…</p>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">✕</span>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
Expected result
Home shows the dark header with Home highlighted, a purple line under the Layout Lab heading, three page paragraphs without borders, two link cards and one footer paragraph with a dashed purple border. Guide shows the same header and footer around a framed Guide panel with Overview, Step 1, Step 2 and Step 3 links; the Guide link in the header stays highlighted on guide/2. Every page heading has the purple line. Hide steps collapses the step links and changes the button to Show steps, and they stay collapsed when you tap Next step.
The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.
C# companion practice
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
// The @layout directive of each component in LayoutLab (null = no directive).
var layoutOf = new Dictionary<string, string?>
{
["MainLayout"] = null,
["GuideLayout"] = "MainLayout",
["Home"] = null,
["Guide"] = "GuideLayout"
};
string[] pages = ["Home", "Guide"];
const string DefaultLayout = "MainLayout";
foreach (var page in pages)
{
Console.WriteLine($"{page,-6} -> {string.Join(" > ", Chain(page, layoutOf))}");
}
// Each layout writes @Body where the next part goes, from the outside in.
var rendered = "Guide content";
foreach (var layout in Chain("Guide", layoutOf).AsEnumerable().Reverse().Skip(1))
{
rendered = layout == "MainLayout" ? $"[header | {rendered} | footer]" : $"[steps | {rendered}]";
}
Console.WriteLine($"Guide renders as {rendered}");
// The common mistake: @layout MainLayout in the root _Imports.razor also reaches MainLayout itself.
var broken = new Dictionary<string, string?>(layoutOf) { ["MainLayout"] = "MainLayout" };
Console.WriteLine($"If MainLayout has @layout MainLayout: {string.Join(" > ", Chain("Home", broken))}");
Console.WriteLine();
// CSS isolation: one stable attribute per component, added to the selectors of its .razor.css file.
var scope = Scope("LayoutLab", "Layout/MainLayout.razor");
Console.WriteLine($"MainLayout scope: {scope}");
foreach (var selector in new[] { "header", "p", "nav ::deep a.active", "main ::deep h1" })
{
Console.WriteLine($"{selector,-20} => {Rewrite(selector, scope)}");
}
// The attribute goes on elements written in MainLayout.razor, not on elements from pages or child components.
var elements = new (string Where, string Tag, string? Scope)[]
{
("MainLayout footer", "p", scope),
("Home.razor", "p", null),
("NavLink output", "a", null)
};
foreach (var element in elements)
{
var carries = element.Scope == scope;
Console.WriteLine($"<{element.Tag}> from {element.Where}: carries {scope} = {carries}");
}
// Walks from the page through each @layout. A page without @layout gets DefaultLayout.
List<string> Chain(string component, Dictionary<string, string?> layouts)
{
var chain = new List<string> { component };
var next = layouts[component] ?? (pages.Contains(component) ? DefaultLayout : null);
while (next is not null)
{
if (chain.Contains(next))
{
chain.Add("(loop: " + next + " wraps itself forever)");
break;
}
chain.Add(next);
next = layouts[next];
}
chain.Reverse();
return chain;
}
// "b-" and ten characters from a hash of the assembly name and the file path.
static string Scope(string assembly, string path)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(assembly + "/" + path));
const string alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
return "b-" + new string(bytes.Take(10).Select(b => alphabet[b % alphabet.Length]).ToArray());
}
// Without ::deep the attribute goes on the last part. With ::deep it goes on the part before ::deep.
static string Rewrite(string selector, string scope)
{
var attribute = $"[{scope}]";
var deep = selector.IndexOf("::deep", StringComparison.Ordinal);
if (deep < 0) return selector + attribute;
var before = selector[..deep].TrimEnd();
var after = selector[(deep + "::deep".Length)..].TrimStart();
return before + attribute + " " + after;
}
C# practice output
Home -> MainLayout > Home Guide -> MainLayout > GuideLayout > Guide Guide renders as [header | [steps | Guide content] | footer] If MainLayout has @layout MainLayout: (loop: MainLayout wraps itself forever) > MainLayout > Home MainLayout scope: b-ecgrkojuna header => header[b-ecgrkojuna] p => p[b-ecgrkojuna] nav ::deep a.active => nav[b-ecgrkojuna] a.active main ::deep h1 => main[b-ecgrkojuna] h1 <p> from MainLayout footer: carries b-ecgrkojuna = True <p> from Home.razor: carries b-ecgrkojuna = False <a> from NavLink output: carries b-ecgrkojuna = False
Do not put @layout MainLayout in the root _Imports.razor: MainLayout would receive it too and wrap itself. A rule in a .razor.css file reaches child components and pages only through ::deep.