Re: [w3c/webcomponents] Provide a lightweight mechanism to add styles to a custom element (#468)

To state the "Styling elements that do not otherwise need a shadow root" use case in a way that is more custom elements-centric:

It's common for custom elements to want to come with default styles---very similar to the "user agent stylesheet" for built-in elements.

You might think that the way to do this is to ship `my-element.css` in addition to `my-element.js`, with contents like `my-element { display: block; }`. (Or something much more complicated, for my-button.)

However, this does not work for two reasons:

- Most importantly, because it does not work inside shadow trees. When you use a `<button>` inside a shadow tree, it is styled, but with the above solution, a `<my-element>` inside a shadow tree stays `display: inline`, since the `my-element` selector cannot reach inside shadow trees.

- Less importantly, but still interestingly, is that the precedence of such stylesheets is higher than the usual precedence of "user agent stylesheets" in the cascade. This has various subtle undesirable side effects.

The solution proposed here lets custom elements come prepackaged, at definition time without any external dependencies, with default "user agent" level stylesheets. It also allows modifications such as styling conditional on the presence or absence of an attribute, e.g.

```js
customElements.define("my-button", MyButton, { styles: `
  * { display: inline-block; }
  *[disabled] { color: gray; }
`);
```

> Allowing styles to be passed in as a string at definition time is a path to allowing constructible stylesheets to be passed in later.

This doesn't actually require constructible stylesheets; engines can memoize on the string values. Last time this was discussed constructible stylesheets were more useful just to make the sharing explicit to the developer, and don't provide much, if any, advantage for the engine.

---

Does this help, @rniwa?

---
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/468#issuecomment-214920775

Received on Tuesday, 26 April 2016 23:39:48 UTC