Observe current/computed style changes (StyleObserver)

Not sure if this falls here or under APIs… This is related to A way to observe changes in CSS custom properties The idea is to have an observer, similar to Resize/Intersection/Mutation(Observer) that gets triggered when certain computed CSS properties of an elements are changed.

It’s very difficult to implement this with MutationObservers without a big performance penalty, while internally the browsers already track these changes.

2 Likes

Could you describe a use-case?

Yes, the use case is describing new behaviors using custom CSS properties, and even using them to polyfill not-yet-supported standard properties.

Just came here to suggest the same thing.

Polyfills are indeed one use case. But IMO the main one is custom elements that need to propagate such changes to the appropriate child / shadow DOM node, or even rewrite them completely.

Examples:

  • Implementing a custom element that works like <fieldset>, where border isn’t applied to the whole element, but to the shadow DOM element wrapping the contents.
  • Similarly, a border on a tabs component wouldn’t be useful around the whole component, but should set the border of the tabs and the tab panels.
  • To direct where a background declaration should be applied. E.g. right now there are dialog/popup components, where setting the background sets the backdrop color instead of the dialog background because of how they were implemented.
  • To implement high-level custom properties that control multiple declarations, e.g. --tabs-placement: [top | right | bottom | left ], --size: [small | medium | large], --pill: [on | off ] which are currently typically implemented as attributes against TAG guidelines. I linked to Shoelace, but other component libraries are no different, Shoelace just has more linkable docs. :slight_smile: This is not something that can be solved with ::part().

Besides propagating declarations to the appropriate child, there is also the opposite: listening to style changes on the children and adjusting ancestors appropriately. E.g. imagine a <pie-chart> component that uses <pie-slice> children to define the different segments, where a shadow <canvas> or conic-gradient background on the parent was used to render the pie chart. This is not implementable without the ability to listen to background changes on <pie-slice> and redraw the chart. And unlike propagating to children, this is not something that can be hacked via inherit and display: contents.

If a generic observer would be too hard, perhaps there could be something specifically for custom elements and slotted elements, like attributeChangedCallback but for CSS properties.

Cross posted to Houdini

3 Likes