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

Responsive Design in Blazor

Apply CSS media queries and responsive grid systems within the Blazor component model.

Responsive Design in Blazor

In this lesson, you will learn how to build fluid, device-aware user interfaces by combining CSS media queries with Blazor’s component-based architecture.

Responsive design is about ensuring your UI adapts gracefully to various screen sizes. While traditional web development relies heavily on global CSS, Blazor allows us to make our components self-contained and context-aware.

Using Media Queries with Component Styling

Since we previously covered Component Scoping and Encapsulation, you know that using scoped CSS files (e.g., MyComponent.razor.css) ensures your styles only apply to that specific component. You can leverage media queries inside these files to change your layout dynamically based on the viewport width:

/* MyComponent.razor.css */
.card-container {
    display: flex;
    flex-direction: column; /* Default: Mobile-first */
}

@media (min-width: 768px) {
    .card-container {
        flex-direction: row; /* Tablet and desktop */
    }
}

Dynamic Grid Systems

You can also use Blazor’s Conditional CSS Class Binding to apply grid-system classes (like those found in Bootstrap or CSS Grid) based on component logic. If you are building a dashboard, you might want to switch between a list and a grid based on a state variable or window size:

<div class="@GetLayoutClass()">
    <div class="item">Data Point A</div>
    <div class="item">Data Point B</div>
</div>

@code {
    private string GetLayoutClass() 
    {
        // You could inject a JS Interop service here to 
        // detect window size, or use pure CSS grid areas.
        return "grid-container";
    }
}

By keeping your media queries within the scoped CSS file, you ensure that your responsive logic stays coupled to the specific component. This avoids the "spaghetti CSS" problem where changing a global style breaks your navigation or footer components. Always design for mobile first, then use min-width queries to progressively enhance the layout as more screen real estate becomes available.

Key Takeaway: Use scoped CSS with media queries to encapsulate responsive behavior directly within your Blazor components, ensuring a clean and maintainable UI architecture.