Shadow CSS; Theming Components with CSS Variables
Shadow CSS
Styles defined within the shadow root of a custom element are scoped to that element, but you can also style the host element from within the shadow DOM using the :host
selector.
:host {
display: block;
background-color: var(--bg-color, #f0f0f0);
}
:host([highlighted]) {
background-color: var(--highlight-color, #ffff00);
}
Theming Components with CSS Variables
You can use CSS variables (also known as custom properties) to make your components themable. Define the variables within the shadow root and allow users to override them from the outside.
:host {
--bg-color: #f0f0f0;
--text-color: #333;
--highlight-color: #ffff00;
display: block;
background-color: var(--bg-color);
color: var(--text-color);
padding: 10px;
}
Then, users can override the variables when using the component:
<my-element style="--bg-color: #007bff; --text-color: white; --highlight-color: #00ff00;">
Custom themed content
</my-element>
This allows for easy theming and customization of your Web Components.