Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use global css styles in shadow dom

Tags:

Shadow dom encapsulate css styles, selectors don't cross the shadow boundary.

Question: How to use global common css styles in shadow dom?
(suppose there are some common css styles which will be used across all pages (e.g.: font-family, h1, h2, clear, reset ...), how to make it works in shadow dom?)

like image 625
Jiubao Avatar asked Feb 29 '16 07:02

Jiubao


People also ask

Does shadow DOM inherit CSS?

Nope! As written in the spec: The top-level elements of a shadow tree inherit from their host element. What this means is that inheritable styles, like color or font-family among others, continue to inherit in shadow DOM, will pierce the shadow DOM and affect your component's styling.

How do you style elements inside shadow DOM?

The element to which shadow DOM is attached is known as the host. To style the host, use the :host selector. Inheritable properties of the host element will inherit down the shadow tree, where they apply to the shadow children.


1 Answers

I've just struggled with the same problem as an original issue, namely: defining once some global rule for, say, <h3> element and benefit from that within any/many ShadowDOMs.

No, css-variables are not suited well for this thing, since even if I've defined once, say, font and color variables for <h3>, I'll still need to go over each and every shadowed stylesheet and add a CSS rule consuming them.

At the point of writing this (yes, we are 2019 now) the shortest standardized solution is indeed importing some global common CSS. Works perfectly in Chrome, Firefox and Anaheim (Edge on Chromium).

It still requires to add an @import rule in each and every component, so still costy (from coding/maintenance POV, the stylesheet fetched only once), but that's the lowest price we can pay now.

like image 54
GullerYA Avatar answered Sep 24 '22 12:09

GullerYA