MediaQuery Overview
The MediaQuery component for Blazor allows you to react when the user changes the size of the browser.
The MediaQuery component is part of Telerik UI for Blazor, a
professional grade UI library with 100+ 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:
- Add the
<TelerikMediaQuery>
tag to your razor page. - Set the
Media
parameter to a CSS media query to be matched. Use one component instance for each media query. - Use the
OnChange
event to determine when theMedia
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).
You should have default values for the flags in your application that define the preferred state or layout. Depending on the browser and the media query setup, it is possible that no
OnChange
event will fire when the app initializes, so the app should have a reasonable default state.