[csswg-drafts] Support for building an optimal, nested CSSStylesheet programmatically (#13367)

bahrus has just created a new issue for https://github.com/w3c/csswg-drafts:

== Support for building an optimal, nested CSSStylesheet programmatically ==
I've been told this should be proposed [here](https://github.com/whatwg/dom/issues/1442) (I guess).

### What problem are you trying to solve?

If a web component doesn't use ShadowDOM, but nevertheless wishes to provide a CSS Module to style the light children DOM elements that the web component generates, it would be natural, with the now shipping nested CSS support, to simply wrap the styles inside a selector that specifies the name of the custom element.  The problem is, especially with scoped custom element registries, that name may not be uniform across all usages.  Also, many web component libraries explicitly suggest using separate file to specify the name of the custom element.

It would also be quite useful to be able to use the same CSS Module, one for a custom element that doesn't use shadow DOM, one that does, that implements nearly identical content.

So we need a way to be able "wrap" the styles with a dynamic outer selector (typically the dynamic name of the custom element).

### What solutions exist today?

I asked Claude AI how it would do it.  It suggests:

```JavaScript
function nestStyleSheet(originalSheet, outerSelector) {
  const newSheet = new CSSStyleSheet();
  
  // Build nested CSS text
  let nestedRules = [];
  
  for (const rule of originalSheet.cssRules) {
    nestedRules.push(rule.cssText);
  }
  
  // Wrap all rules in the outer selector using nested CSS syntax
  const nestedCSS = `${outerSelector} {
  ${nestedRules.join('\n  ')}
}`;
  newSheet.replaceSync(nestedCSS);
  return newSheet;
}
```

This is probably all just fine, but I wonder if that means excessive string parsing?  The browser now needs to reparse the entire contents again, rather than just cloning parsed "nodes".

### How would you solve it?

Something like 

```JavaScript
   new CssStyleSheet("outerSelector", {wraps: originalSheet}}
```

### Anything else?

_No response_

Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/13367 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Sunday, 18 January 2026 20:50:55 UTC