Skip to content
Advertisement

How to avoid repetition of CSS properties across multiple Web Components

I’m building with Web Component without any 3rd-party framework.

And I have vanilla <button> in several of my components, and I have to reset EVERY ONE of them before I do my custom styling on them because resetting it once at a root level doesn’t work since the properties involved are not one of inheritable styles that pierce through shadow dom:

button {
   appearance: none;
   background: none;
   border: none;
   ...
}

What do you all think is the current best and widely supported way to avoid this repetition?

I have looked at the Constructable Stylesheets, but it’s poorly supported in Firefox, which is my main browser. I also considered CSS Custom Properties, but that would still lead to repetition of background, border etc. properties everywhere right?

Advertisement

Answer

Constructable stylesheets are designed to address, among others, exactly this problem you’re having.

There has been experimental support for constructable stylesheets in Firefox since version 73 (Feb. 2020). Not sure why it hasn’t left the experimental feature status for more than 2 years now.

You can enable it by setting layout.css.constructable-stylesheets.enabled to true in about:config.

Until it’s no longer experimental, you can use a polyfill.

The next thing that will help you reduce redundancy is called CSS Module Scripts. From that page:

Deduplication: if the same CSS file is imported from multiple places in an application, it will still only be fetched, instantiated, and parsed a single time.

Unfortunately, that also hasn’t landed in Firefox yet (see this tracking bug), but already in the specification.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement