Day 18: inheritable styles and web components
posted on
It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.
We already know that we can encapsulate styles within a web component by adding elements along with the styles to the shadow DOM. Global style declarations from outside don’t overwrite styles inside the web component.
Shadow DOM doesn't provide total encapsulation, though.
If you look at the following component, you’ll notice that it uses the same font as the rest of the page, even though I haven't applied any styles to the web component. If styles were completely encapsulated, I would expect the component to use a default font like Times, but the web component inherits styles from its parent elements.
HTML:
<shadow-component></shadow-component>
JS:
class ShadowComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `<div>Hello World!</div>`
}
}
customElements.define('shadow-component', ShadowComponent);
If I wrap the component in a <div>
and a set a color
on the div, the color of the text inside the web component changes as well. That's because top-level elements of a shadow tree inherit from their host element. In other words, inhertiable styles will be passed to the shadow DOM.
.parent {
color: red;
}
<div class="parent">
<shadow-component></shadow-component>
</div>
Further reading
- Styling: Styles Piercing Shadow DOM
- Day 10: global styles and web components
- Day 28: custom properties and web components
- Day 45: the specificity of ::slotted() content
- Day 60: the ::part() pseudo-element
Overview: 100 Days Of More Or Less Modern CSS