DEV Community

Cover image for Blazor CSS-isolation a ::shallow quick fix..
netsi1964 🙏🏻
netsi1964 🙏🏻

Posted on

Blazor CSS-isolation a ::shallow quick fix..

Vanilla CSS, the pure not-infected by frameworks, is IMHO the best way to do CSS. With all the nice features like native nesting and custom properties (CSS variables) it seems to me that we have what we need. That however seems not to be the understanding of many frameworks, like Blazor, Angular and others.

The Blazor CSS-isolation issue

Here I want to share a quick fix understanding when fighting the Blazor CSS effects to your css. It seems to actually be a valid solution.

Add ::deep after your component root css class

It is as simple as that! (it seems).

The Blazor CSS-isolation technique

Blazor uses like other frameworks (Angular for instance) a technique of injecting a unique attribute on component HTML. It looks like this: b-khlzklwsq4. It is a "b" and then a random 10 chars long GUID sort of string. This combined with the rewriting of you pretty vanilla CSS for the component allows Blazor to have scoped css. CSS which will not break other components (but only itself ;-)).

So if I have my css:

.my-component {
  outline: 1px black solid;
}
.my-component *:focus {
  outline: none;
}
Enter fullscreen mode Exit fullscreen mode

Blazor will pass it at runtime into:

.my-component[b-khlzklwsq4] {
  outline: 1px black solid;
}
.my-component *:focus[b-khlzklwsq4] {
  outline: none;
}
Enter fullscreen mode Exit fullscreen mode

However I need to target any element which has focus, not just elements in focus which has the attribute b-khlzklwsq4!

My rule-of-fix-::deep is then to simply add a ::deep after the main component selector (.my-component) and get this:

.my-component {
  outline: 1px black solid;
}
.my-component ::deep *:focus {
  outline: none;
}
Enter fullscreen mode Exit fullscreen mode

That way I instruct Blazor: "Please do not manipulate any of my CSS other than the main selector (.my-component). It seems to work! :-)

.my-component[b-khlzklwsq4] {
  outline: 1px black solid;
}
.my-component *:focus {
  outline: none;
}
Enter fullscreen mode Exit fullscreen mode

That in fact was my ::shallow quick-fix of the broken Blazor CSS-isolation functionality!

Top comments (0)