Learn Blazor Β· 7/15

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

  1. Create the Layout File:
    Inside your Shared folder (or Layout folder in newer templates), create a file named MainLayout.razor.

  2. Inherit the Base:
    You must inherit from LayoutComponentBase.

  3. Define the Structure:

razor
@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:

  1. Globally (The Standard):
    Open _Imports.razor (this file makes directives available to the whole folder tree). Add this line:

    razor
    @layout MainLayout

    Now, every component in your app uses this layout by default.

  2. 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.

  1. Public Area: Just a header and content.
  2. 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

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:

  1. Outer Layer: MainLayout (Header/Footer)
  2. Middle Layer: AdminLayout (Admin Sidebar) gets injected into MainLayout's @Body.
  3. Inner Layer: UserList.razor gets injected into AdminLayout'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.

css
.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.

  1. Component: Counter.razor
  2. Style: Create a file named Counter.razor.css in the same folder.

Inside Counter.razor.css:

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:

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) or Pages/_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.

bash
npm init -y

Step 2: Install Tailwind

bash
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

Step 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).

javascript
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:

css
@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:

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:

html
<link href="css/app.css" rel="stylesheet" />

Step 7: Run it

Open a separate terminal window and run:

bash
npm run build:css

Now, 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

  1. Main Layouts (@inherits LayoutComponentBase) prevent you from copy-pasting navbars. Use @Body to decide where content goes.
  2. Nested Layouts allow complex hierarchies (Admin vs. User) without duplicating the core HTML.
  3. CSS Isolation (.razor.css) adds unique IDs to HTML elements so styles don't conflict. Use ::deep to style children.
  4. Tailwind CSS requires a separate NPM process to watch your .razor files and generate the final CSS.

πŸ“š References & Further Reading

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 category is 'Electronics'.
  • The product is in stock (i.e., stock is 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:

javascript
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:

  1. .filter(product => product.category === 'Electronics' && product.stock > 0): This step iterates through the products array and creates a new array containing only the objects that satisfy both conditions: the category is 'Electronics' and the stock is greater than zero.
  2. .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.
  3. .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. The accumulator starts at 0 and adds each currentValue (a discounted price) to it, resulting in the final total.

Given the provided products data, the function should return 1444.5.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.