Layouts & UI Styling
7 min read
π¨ Layouts & UI Styling: The Art of Architecture
Welcome back, developer! π If components are the bricks of your application, Layouts are the blueprints, and Styling is the paint.
Imagine building a skyscraper. You wouldn't redraw the architectural plans for the foundation, the plumbing, and the elevators for every single floor, right? That would be madness. Youβd create a core structure and then customize the interiors of each floor.
In the early days of web dev, we actually did copy-paste headers and footers onto every HTML page. If the boss wanted to change the logo, you had to edit 50 files. It was a dark time. We don't talk about it. π€«
Today, we are going to learn how Blazor solves this with Layouts and how to make it look professional with CSS Isolation and External Frameworks.
1. Creating and Applying Main Layouts ποΈ
The Definition
A Layout in Blazor is a specialized component that inherits from LayoutComponentBase. It defines the UI structure that is shared across multiple pages (like navigation bars, footers, and sidebars).
The Problem
You have 10 pages. They all need the same Navigation Bar at the top and the same Copyright Footer at the bottom.
- Without Layouts: You copy the
<NavMenu />and<footer>code into all 10 files. - The Issue: If you need to add a "Login" button to the nav, you have to edit 10 files. This violates the DRY (Don't Repeat Yourself) principle.
The Solution: MainLayout.razor
Blazor uses a "hole-in-the-donut" approach. You create a layout (the donut), and tell Blazor where to stick the specific page content (the hole). That "hole" is represented by the syntax @Body.
Step-by-Step Implementation
Create the Layout File:
Inside yourSharedfolder (orLayoutfolder in newer templates), create a file namedMainLayout.razor.Inherit the Base:
You must inherit fromLayoutComponentBase.Define the Structure:
@inherits LayoutComponentBase
<div class="page">
<div class="sidebar">
<NavMenu /> <!-- This stays on every page -->
</div>
<main>
<div class="top-row px-4">
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
</div>
<article class="content px-4">
<!-- π THIS IS THE MAGIC PART -->
@Body
<!-- The content of the page you navigate to renders here -->
</article>
</main>
</div>What is happening under the hood?
When you navigate to /counter, Blazor takes the content of Counter.razor and injects it exactly where you wrote @Body inside MainLayout.razor.
Applying the Layout
You can apply a layout in two ways:
Globally (The Standard):
Open_Imports.razor(this file makes directives available to the whole folder tree). Add this line:razor@layout MainLayoutNow, every component in your app uses this layout by default.
Per Page (The Override):
Sometimes a Login page shouldn't have a sidebar. You can override the global setting inside a specific page (e.g.,Login.razor):razor@page "/login" @layout LoginLayout <h1>Please Log In</h1>
2. Nested Layouts for Complex UI Structures π§
The Definition
Nested Layouts occur when a Layout component itself uses another Layout.
The Problem
Scenario: You have a massive application.
- Public Area: Just a header and content.
- Admin Area: Needs the header, BUT also needs a secondary "Admin Sidebar" with tools.
If you make a separate AdminLayout that copies the header code from MainLayout, you are back to duplicating code. If the header changes, you have to fix it in two places.
The Solution
Make AdminLayout inherit from LayoutComponentBase, but wrap its content in MainLayout.
File: AdminLayout.razor
@inherits LayoutComponentBase
@layout MainLayout
<!-- π It uses MainLayout as its parent! -->
<div class="admin-panel">
<aside class="admin-tools">
<button>Delete Database (Do not click)</button>
<button>Ban User</button>
</aside>
<div class="admin-content">
<!-- The specific admin page renders here -->
@Body
</div>
</div>The Hierarchy:
- Outer Layer:
MainLayout(Header/Footer) - Middle Layer:
AdminLayout(Admin Sidebar) gets injected intoMainLayout's@Body. - Inner Layer:
UserList.razorgets injected intoAdminLayout's@Body.
Fun Fact: This is like Russian Nesting Dolls (Matryoshka dolls), but for code. If you nest too deep (5+ layers), you will likely forget where you are and cry. Keep it shallow! πͺ
3. CSS Isolation: Scoping Styles Safely π‘οΈ
The Definition
CSS Isolation allows you to define styles that apply only to a specific component, preventing them from leaking out and affecting other parts of the app.
The Problem: The "Global Namespace" War
You create a nice component and style a class called .card.
.card { background-color: blue; }Suddenly, the Bootstrap .card used in your navigation bar turns blue. Or the Credit Card form turns blue. Global CSS is a free-for-all deathmatch where the last stylesheet loaded wins.
The Solution: .razor.css
Blazor allows you to create a CSS file that matches the component name.
- Component:
Counter.razor - Style: Create a file named
Counter.razor.cssin the same folder.
Inside Counter.razor.css:
h1 {
color: red;
font-family: 'Comic Sans MS'; /* Please don't actually do this */
}The Result:
Only the <h1> inside the Counter component becomes red. The <h1> on your Home page remains untouched.
How it works (Under the hood) π§
When you build your app, Blazor rewrites your HTML and CSS.
It generates a unique ID (like b-3x7y5z) for the component.
Your HTML transforms from:<h1>Counter</h1>
To:<h1 b-3x7y5z>Counter</h1>
Your CSS transforms from:h1 { color: red; }
To:h1[b-3x7y5z] { color: red; }
The ::deep Combinator (Industry Standard Tip)
Sometimes you use a child component inside your parent component, and you want to style the child from the parent's isolated CSS. By default, isolation blocks this.
To pierce the veil, use ::deep.
Inside Parent.razor.css:
/* Styles any h1 inside this component OR its children */
::deep h1 {
color: purple;
}4. Integrating External CSS Frameworks (Tailwind, Bootstrap) π
You don't have to write all CSS from scratch. In fact, most pros don't.
Bootstrap (The Classic)
Bootstrap usually comes pre-installed in the default Blazor template.
- Where is it? Look in
wwwroot/index.html(WASM) orPages/_Layout.cshtml(Server). You'll see the<link>tag. - Usage: Just use standard classes like
<div class="btn btn-primary">. - Pros: Easy, grid system is solid.
- Cons: Your site looks like every other site built in 2015 if you don't customize it.
Tailwind CSS (The Modern Standard) πͺοΈ
Tailwind is a "utility-first" framework. Instead of writing .sidebar { width: 200px; float: left; }, you write <div class="w-[200px] float-left">. It's incredibly popular in the industry right now.
Setting up Tailwind in Blazor (The Hardest Part of this Guide):
Note: Blazor doesn't process JS/CSS natively like React/Next.js, so we need a standalone build step.
Step 1: Initialize NPM
Go to your project root folder (where the .csproj is) in the terminal.
npm init -yStep 2: Install Tailwind
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss initStep 3: Configure Tailwind
Open the generated tailwind.config.js. You must tell it where to look for your HTML/Razor code so it can "tree-shake" (remove unused CSS).
module.exports = {
content: [
'./**/*.{razor,html,cshtml}'
],
theme: {
extend: {},
},
plugins: [],
}Step 4: Create the CSS Source
Create a file Styles/app.css (create the folder if needed). Add the Tailwind directives:
@tailwind base;
@tailwind components;
@tailwind utilities;Step 5: Build the CSS
You need to compile that app.css into a standard CSS file inside wwwroot.
Add a script to your package.json:
"scripts": {
"build:css": "npx tailwindcss -i ./Styles/app.css -o ./wwwroot/css/app.css --watch"
}Step 6: Link it
In your index.html (or App.razor / _Layout.cshtml), replace the default css link with:
<link href="css/app.css" rel="stylesheet" />Step 7: Run it
Open a separate terminal window and run:
npm run build:cssNow, whenever you save a .razor file, Tailwind will regenerate your CSS instantly.
Industry Simulation: In a real job, your CI/CD pipeline (GitHub Actions/Azure DevOps) will run the CSS build command before compiling the .NET app. Never commit the generated CSS to the repo if you can avoid it; commit the source and let the build server do the work!
π Summary
- Main Layouts (
@inherits LayoutComponentBase) prevent you from copy-pasting navbars. Use@Bodyto decide where content goes. - Nested Layouts allow complex hierarchies (Admin vs. User) without duplicating the core HTML.
- CSS Isolation (
.razor.css) adds unique IDs to HTML elements so styles don't conflict. Use::deepto style children. - Tailwind CSS requires a separate NPM process to watch your
.razorfiles and generate the final CSS.
π References & Further Reading
- Official MS Docs: Blazor Layouts
- Official MS Docs: CSS Isolation
- Tailwind CSS Installation
- MudBlazor (A popular UI Component library specifically for Blazor - check this out if you hate writing CSS entirely).
Next Up: We will dive into Forms and Validation. Get your keyboards ready! β¨οΈ
Challenge
You are provided with an array of product objects. Each object has the structure: { id: number, name: string, price: number, category: string, stock: number }.
Write a function named calculateTotalValue that takes this array of products as input.
The function should calculate the total value of all products that meet the following criteria:
- The product's
categoryis 'Electronics'. - The product is in stock (i.e.,
stockis greater than 0).
Before summing the prices, apply a 10% discount to each qualifying product.
You must implement the solution using a single, chained sequence of the filter, map, and reduce array methods.
Expected result
The submitted code should define the calculateTotalValue function that correctly chains filter, map, and reduce to compute the total value.
The correct implementation will look like this:
function calculateTotalValue(products) {
return products
.filter(product => product.category === 'Electronics' && product.stock > 0)
.map(product => product.price * 0.9)
.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
}Breakdown:
.filter(product => product.category === 'Electronics' && product.stock > 0): This step iterates through theproductsarray and creates a new array containing only the objects that satisfy both conditions: the category is 'Electronics' and the stock is greater than zero..map(product => product.price * 0.9): This step takes the filtered array of products and creates a new array. Instead of product objects, this new array contains the calculated discounted price (original price reduced by 10%) for each product..reduce((accumulator, currentValue) => accumulator + currentValue, 0): This final step takes the array of discounted prices and reduces it to a single value. It does this by summing up all the prices. Theaccumulatorstarts at0and adds eachcurrentValue(a discounted price) to it, resulting in the final total.
Given the provided products data, the function should return 1444.5.