Append Styles to a Custom Element (Beta)
Third-party web components can contain custom elements that are created in shadow DOM or light DOM. For shadow DOM, open mode is more widely used than closed mode. To find out if the third-party web component you're working with is using a particular shadow mode, refer to the web component documentation. Alternatively, view the web component source and find the attachShadow({mode: 'closed|open'})
method. A web component that uses light DOM doesn't use the attachShadow()
method.
After you identify the DOM model for the third-party web component, you can decide how to style the custom element and its internals.
Using shadow DOM, a custom element can't inherit styles from its container component. Similarly, styles that are defined within the custom element don't bleed out. You can't append styles to a custom element's shadow DOM in closed mode. For example, this.refs.myEl.shadowRoot
returns null.
Many web component authors implement styles to the custom element by appending the <style>
tag to the shadow root. View the web component source and find lines similar to these ones. These styles are scoped within the shadow root.
To append styles in closed mode, you can use CSS variables (custom properties), classes, or shadow parts. We don't recommend using JavaScript to define CSS styles besides the shadow root styling implementation on third-party web components.
A web component author lets you override a style in the shadow root if they include a CSS custom property like this.
Check the third-party web component source or documentation for available CSS custom properties and shadow parts that you can use to style the custom element in your component.
Since CSS custom properties bleed through the shadow DOM, you can override the styling in your host component.
Let's say the third-party web component provides the border: var(--my-border, 1px solid black);
border styling with a CSS custom property --my-border
. In your host component, use the CSS custom property with your own value.
If you want to style the host element of a third-party custom element, use a selector for the custom element in your .css
file, for example, c-custom-el { background-color: red; }
.
The c-custom-el
selector applies a red background to the content of the custom element.
The custom element renders like this.
Unlike shadow DOM, light DOM enables styling from the root document to target a DOM node and style it. So the styles on a container component cascade into the nested custom element's light DOM. The styles on a custom element that's rendered in light DOM are also applied to its container components until a shadow boundary is encountered.
If the third-party web component uses light DOM, you can style the custom element's internals using a class in a .css
file. To scope the style within the custom element, include your styles using a .scoped.css
file in your component bundle.
In your css file, provide the custom styling.
See Also