Making a Shadow-DOM component themable

Nolan Lawson's emoji-picker-element is a small custom element that is easy to drop into an app. The difficulty starts once a consumer wants it to match their own interface. As Lawson put it, the question of how to let users restyle the component was not obvious: what happens when someone wants a different background color, larger emoji, or another font in the input field?

Four approaches to exposing styles

Lawson catalogues four routes, each offering a different degree of control to the component's consumers:

  1. CSS custom properties. Declarations such as background: var(--background, white); act as styling hooks, because custom properties cross the Shadow DOM boundary.
  2. Pre-built variations. A class attribute on the custom element pairs with pseudo selectors inside the shadow tree, e.g. :host(.dark) { background: black; }.
  3. Shadow parts. The component marks up styleable internals with a part attribute — <span part="foo"> — which outside CSS can target via custom-component::part(foo) { }.
  4. Forced user styles. Shadow DOM is not a hard seal: element.shadowRoot is reachable, so a <style> can always be injected.

One additional channel is worth naming: DOM that is slotted into place can be styled by outside CSS.

The cost of a bespoke styling API

None of the four options satisfies the author. Scoped styles are a good idea, and the Shadow DOM is the web platform's nearest equivalent, but every listed technique pushes the component author toward designing and documenting a styling API of their own, without encouraging consistency between components. To Chris Coyier, the DOM already functions as a styling API, so the scoping protection should come with a straightforward way to reach inside and apply styles while keeping the cascade. He floats two hypotheticals for that: using the dash-separated custom-element name directly (my-custom-elemement li { }), or an explicit at-rule form like @shadow my-custom-element li { }. Constructable Stylesheets, in his view, do not make this any easier.

It shows up in practice

The problem is not academic; it surfaces in everyday work.

Heyyyy Web Component folks, I’m modernizing my old <podcast-player> custom element (now built with lit-element and has better a11y and TimeJumping), but I left it as a PR because I have a few questions on how to best approach styling and customization. https://t.co/UecDytLUgF

— Dave Rupert (@davatron5000) January 20, 2021

The thread did not produce a clearly good answer for how to handle the styling. The practical fallback is to do nothing extra: ship minimal styling, let consumers restyle their own copy of the component however they like, or force styles in for full freedom.