This content originally appeared on Go Make Things and was authored by Go Make Things
One of the more common questions I get around Web Components is how to style them.
The Shadow DOM is a big part of why Web Components are often hard to style. Because it encapsulates your HTML from the main DOM, your nested HTML doesn’t inherit your global CSS.
When you have a robust design system, this makes everything a lot harder. So much so that I consider the Shadow DOM an anti-pattern in most situations.
The trick to stress-free styling of Web Components is to keep all of your HTML in the light DOM.
Either nest it in your custom element and progressively enhance it…
<show-hide>
<button trigger>Show More</button>
<div content>
Now you see me, now you don't!
</div>
</show-hide>
Or render it into the light DOM instead of the shadow DOM…
customElements.define('say-hi', class extends HTMLElement {
/**
* Create a new instance
*/
constructor () {
super();
this.innerHTML = `<p>Hey there, ${this.getAttribute('first-name')}!</p>`;
}
// ...
});
Your HTML will inherit your global CSS automatically.
If you need to add some custom styles or overrides, you can use the custom HTML element to add a bit more specificity.
show-hide button {
/* Override the default button styles... */
}
/* Make the paragraph bigger */
say-hi p {
font-size: 1.5rem;
}
In a future article, I’ll talk about when the shadow DOM actually makes sense.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2024-10-17T14:30:00+00:00) Styling web components. Retrieved from https://www.scien.cx/2024/10/17/styling-web-components/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.