Override styles in a shadow-root element

Because of the isolation of styles, which is a feature of Shadow DOM, you cannot define a global CSS rule that will be applied in the Shadow DOM scope.

It could be possible with CSS variables but they should be implemented explicitly in the shadowed component (which is not the case with this 3rd party library).

A workaround is to inject the line of style in the shadow DOM directly.

//host is the element that holds the shadow root:
var style = document.createElement( 'style' )
style.innerHTML = '.the-class-name { property-name: my-value; }'
host.shadowRoot.appendChild( style )

NB: it will work only if the Shadow DOM mode is set to 'open'.


2019 update for Chrome 73+ and Opera 60+

Now it is possible to instantiate a CSSStyleSheet object directly and to affect it to a Shadow DOM or a document:

var sheet = new CSSStyleSheet
sheet.replaceSync( `.color { color: pink }`)
host.shadowRoot.adoptedStyleSheets = [ sheet ] 

Leave a Comment