Course contentsShow
← C#
Lesson 1371 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Advanced Component Styling

Use CSS variables and dynamic style injection for theming applications at runtime.

Advanced Component Styling: Runtime Theming with CSS Variables

In this lesson, you will learn how to implement dynamic, runtime theming in Blazor by binding CSS variables directly to C# component state.

Instead of swapping entire CSS files or relying on heavy pre-processor logic, modern Blazor applications leverage the power of CSS Custom Properties (variables). Because these variables are defined in the DOM, we can inject values from our C# code at runtime, allowing users to adjust color palettes, spacing, or font sizes instantly without a page refresh.

The Mechanism: Dynamic Inline Styles

The core concept is to use the style attribute on a wrapper element to define CSS variables, which then propagate to all child components. By mapping these variables to properties in your Blazor component, you create a reactive link between your application state and the browser's rendering engine.

Consider a simple ThemeWrapper.razor component:

<div style="--primary-color: @PrimaryColor; --font-size: @FontSizeBase;">
    @ChildContent
</div>

@code {
    [Parameter] public string PrimaryColor { get; set; } = "#007bff";
    [Parameter] public string FontSizeBase { get; set; } = "16px";
    [Parameter] public RenderFragment ChildContent { get; set; }
}

In your CSS file, you simply consume these variables as you would any native CSS property:

button {
    background-color: var(--primary-color);
    font-size: var(--font-size);
}

Why This Matters

When the PrimaryColor parameter changes—perhaps due to a user selecting a new theme in a settings menu—Blazor detects the change, updates the style attribute, and the browser immediately recalculates all elements referencing that variable. This avoids the need for manual DOM manipulation or global CSS class toggling, keeping your styling logic encapsulated within the Blazor component lifecycle.

By centralizing these variables in a state container (such as a Scoped Service), you can make your entire application theme-aware while maintaining a clean separation between your C# business logic and your visual presentation.

Key Takeaway: By injecting CSS variables via the style attribute, you can create fully reactive, runtime-customizable themes that synchronize seamlessly with your Blazor component state.