This content originally appeared on Go Make Things and was authored by Go Make Things
Yesterday, we looked at why styling Web Component elements in the shadow DOM sucks, and I shared five different approaches you can use.
Today, we’re going to look at the first of those in-depth: inline CSS.
Let’s dig in!
The example we’ll be using
Let’s imagine we’ve got a <count-up>
element, like this…
<count-up></count-up>
When our JavaScript loads, we instantiate a new Web Component, like this…
// JavaScript
customElements.define('count-up', class extends HTMLElement {
/**
* The class constructor object
*/
constructor () {
// Gives element access to the parent class properties
super();
// Component properties
this.count = 0;
// Create a shadow root
this.root = this.attachShadow({mode: 'closed'});
// Inject the HTML into the shadow DOM
this.root.innerHTML = `<button>Clicked ${this.count} Times</button>`;
// Listen for events
// ...
}
});
Which then renders HTML like this…
<count-up>
#shadow-root (closed)
<button>Clicked 0 Times</button>
</count-up>
We want to style the Web Component’s shadow DOM button to match the rest of global CSS.
button {
background-color: rebeccapurple;
border: 0;
border-radius: 0.25em;
color: white;
font-family: 'PT Serif', sans-serif;
font-size: 1.2em;
padding: 0.25em 0.5em;
}
Using an inline <style>
element
The most straightforward way to style web components is with inline CSS.
You add a <style>
element to the component markup, and style the component elements as desired.
// Inject the HTML into the shadow DOM
this.root.innerHTML =
`<style>
button {
background-color: rebeccapurple;
border: 0;
border-radius: 0.25em;
color: white;
font-family: 'PT Serif', sans-serif;
font-size: 1.2em;
padding: 0.25em 0.5em;
}
</style>
<button>Clicked ${this.count} Times</button>`;
There are, of course, a few big disadvantages with this approach.
First, if you’re including a component as part of a design system or for an existing site or app, you can’t take advantage of existing stylesheets. This approach violates DRY (Don’t Repeat Yourself) principles, and forces you to repeat yourself often.
It may also be perfectly reasonable for developers to style certain aspects of a component (like button colors or size), and this approach gives them no opportunity to do so.
What’s next?
Tomorrow, we’ll look at the next option: CSS variables or custom properties.
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2024-11-05T14:30:00+00:00) Styling Web Component shadow DOM elements with inline styles. Retrieved from https://www.scien.cx/2024/11/05/styling-web-component-shadow-dom-elements-with-inline-styles/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.