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…
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.
Cheers,
Chris
Want to share this with others or read it later? View it in a browser.
0 Komentar untuk "[Go Make Things] Styling Web Component shadow DOM elements with inline styles"