3

Day 18: inheritable styles and web components

 1 year ago
source link: https://www.matuzo.at/blog/2022/100daysof-day18/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Day 18: inheritable styles and web components

posted on October 19., 2022

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.

Demo:

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>

Demo:

See on CodePen.

Further reading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK