I would like to set the CSS breakpoints globally in Blazor. What are some approaches? I prefer something that keeps the code or additional libraries quite simple.
Tooling
1 Reply
I came up with a simple solution. Instead of breakpoints in CSS, I use CSS classes for the different screen formats. I set the screen format with JavaScript.
Example usage of the css classes:
<!-- HelloWorld.razor -->
<div class="hello_world">
hello, world!
</div>
html._screen-xs .hello_world {
color: red;
}
html._screen-s .hello_world {
color: orange;
}
html._screen-m .hello_world {
color: yellow;
}
JavaScript code to set the css classes:
// should be executed before the HTML content, in order to make the first render correctly use the breakpoints
let ScreenFormat = (function create_screen_format() {
let elHTML = window.document.documentElement
return use_breakpoint_class(elHTML, function determine_breakpoint_class([width, height]) {
let breakpointClass
if (width < 864) {
breakpointClass = '_screen-xs'
} else if (width < 1280) {
breakpointClass = '_screen-s'
} else if (width < 1920) {
breakpointClass = '_screen-m'
} else if (width < 3840) {
breakpointClass = '_screen-l'
} else {
breakpointClass = '_screen-xl'
}
return breakpointClass
})
})();
function get_client_size(el) {
return [el.clientWidth, el.clientHeight]
}
function use_breakpoint_class(el, fn_determine_breakpoint_class) {
let breakpoint_class
function initialize() {
let client_size = get_client_size(el)
breakpoint_class = fn_determine_breakpoint_class(client_size)
el.classList.add(breakpoint_class)
}
function update() {
let client_size = get_client_size(el)
let breakpoint_class_new = fn_determine_breakpoint_class(client_size)
if (breakpoint_class_new !== breakpoint_class) {
el.classList.replace(breakpoint_class, breakpoint_class_new)
breakpoint_class = breakpoint_class_new
}
}
initialize()
let resize_observer = new ResizeObserver(function handle_resize() {
update()
})
resize_observer.observe(el)
return {
initialize: initialize,
update: update,
}
}
// should be executed after the Blazor library has been loaded
Blazor.addEventListener('enhancedload', function () {
ScreenFormat.initialize()
})