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

  • The MediaQuery component makes it easy to use C# logic based on the matched media query breakpoints. For example, you can change parameter values, replace a component with a different component or even not render parts of the layout. With CSS alone you can resize parts of the app or hide them visually, but they still render.
  • The MediaQuery component is not designed as a full replacement for responsive design, layout and CSS. You should use them to create your responsive application layouts like with any other web application.

Next Steps

See Also

In this article