MediaQuery Overview

The MediaQuery component for Blazor allows you to react when the user changes the size of the browser.

Telerik UI for Blazor Ninja image

The MediaQuery component is part of Telerik UI for Blazor, a professional grade UI library with 110+ native components for building modern and feature-rich applications. To try it out sign up for a free 30-day trial.

Creating Blazor MediaQuery

To use the TelerikMediaQuery on your page:

  1. Add the <TelerikMediaQuery> tag to your razor page.
  2. Set the Media parameter to a CSS media query to be matched. Use one component instance for each media query.
  3. Use the OnChange event to determine when the Media is matched.
@* Resize a container based on the browser size *@

<TelerikMediaQuery Media="@SmallScreenMediaQuery" OnChange="@((doesMatch) => IsSmallScreen = doesMatch)"></TelerikMediaQuery>
<TelerikMediaQuery Media="@LargeScreenMediaQuery" OnChange="@((doesMatch) => isLarge = doesMatch)"></TelerikMediaQuery>

<div style="width:@GetContainerWidth(); height: 400px; border: 1px solid black">
    Shrink the browser to resize the container.
</div>


@code {
    private bool IsSmallScreen { get; set; }
    private bool isLarge { get; set; }

    private string SmallScreenMediaQuery { get; set; } = "(max-width: 767px)";
    private string LargeScreenMediaQuery { get; set; } = "(min-width: 1199px)";

    private string GetContainerWidth()
    {
        string width = "900px";

        if (IsSmallScreen)
        {
            width = "500px";
        }
        if (isLarge)
        {
            width = "100%";
        }

        return width;
    }
} 

MediaQuery Parameters

Parameter Type and Default value Description
Media string the media query string that will be matched.

Notes

The MediaQuery component facilitates the usage of CSS media queries in your C# code. There are a few points to keep in mind:

  • The MediaQuery component is not a replacement for responsive design, layout and CSS. You should use them to create your responsive application layouts like with any other web application.

  • The MediaQuery component makes it easy to use C# logic based on the breakpoint that matches - such as changing parameter values, replacing a component with a different component or even not rendering a part of the layout (with CSS alone you can resize parts of the app or hide them visually, but they still render).

Next Steps

See Also

In this article