You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Provide a lightweight mechanism to add styles to a custom element #468
Allow a user to define a set of styles to apply to a custom element as an option to customElements.define. Conceptually, providing styles would make the element act as if it had a shadowRoot including a style element with the provided css. The rules used to target the element would be the same as in Shadow DOM.
To style a custom element that does not otherwise need a shadowRoot incurs an unfortunate performance penalty and is cumbersome. A user must create a shadowRoot and put inside it a style element and a slot element. Providing this styling at define time gives the platform an opportunity to optimize beyond what could be achieved when interpreting user code that installs the shadowRoot, style, and slot at construct/connected time. In addition, because the proposed syntax is less code than the alternative, it would likely reduce concern over #426.
Ideally, developers could include styles targeting elements inside Shadow DOM in addition to the element itself. Again, the provided styles would act as if they were in a style that was the first element inside the shadowRoot. This could help address #282 and the feature could be explained as a constructable stylesheet when this feature is added to the platform.
Reacted by Thiago Bustamante, Mads, Bede Overend, Tim van der Lippe, Tung Nguyen, Niklas Higi, Daniel Busłowicz, Masudur Rahman, Caleb Williams, Stephanie Rewis and 12 more
Reacted by Nick Dugger and Joe Pea
Reacted by Stephen Belovarich, Alkis Mavridis, Jack Works and Justin Fagnani
I like this idea a lot. One thing about it that it solves is the issue of wanting to supply a "UA stylesheet" for your custom elements. You can't just do something like my-element { display: block; } because this fails to reach inside shadow roots. When we had deep, you could do something like my-element, * /deep/ my-element { display: block; }, but deep is gone. Also, that formulation is higher priority than the UA stylesheet, as noted in HTML as Custom Elements. (In particular, something like * { display: inline; } should override this "UA stylesheet level" stuff.)
One thing I am still confused on is whether :host is the right name for the selector targeting the specific element being defined. Since we're specifically not talking about inserting a shadow root, and :host is currently defined in terms of shadow DOM, it seems like a bad match to me, and I'd expect something new, more like :element. But others have told me :host is a good idea. If we sufficiently redefined :host as such (@tabatkins, @hayatoito?) then maybe it's OK. I'd still like to understand why we'd do that though.
+1 from me on this idea; I'd wondered about an author-controlled "UA styles" a few years ago, early in the project, and this API surface feels good, better than whatever else I'd come up with.
I presume that the selectors are meant to be interpreted "like" a shadow stylesheet, right? So they only apply to the element and its contents, and don't leak out to the global level? In that case this is pretty easy - just need to specify that the styles are interpreted in the user-agent origin and all of its selectors are scope-contained by the host element.
I think using :host is fine - it has a very similar meaning here to what it does in shadow DOM, and that makes things easier to understand. Do we plan to "hide" the host element, like you get in real shadow DOM? (I think we should, to keep the similarities as high as possible.) If so, then we just need to additionally say that, for the purposes of these selectors, the root element is featureless and matches :host/:host()/:host-context(). (This is more-specific-overriding-general, contradicting the general rule that :host/etc represents nothing outside a shadow tree.)
Question: do we want to necessarily tie this to the registerElement() call? Or do we want to allow embedding this into your global CSS too, so that even if your JS is slow or broken, your page at least doesn't totally break? We'd put it under a @custom-element foo-bar {...} rule or something similar. We'd just need to define an ordering for the JS sheet vs the CSS ones; I suspect the JS sheet should come afterwards, so they'll win in case of conflict.
This way you can retain a reference and add to, remove or modify the css rules in a familiar manner later if required.
Reacted by Trey Shugart, Russell Bicknell, xlaywan, Mike Collins, Ryan Johnson, Michał Skowronek, Nicolás Parada, Stephen Belovarich, Ryan Graham and Owen Buckley
Reacted by Mike Collins, Stephen Belovarich and Alkis Mavridis
See also #376 (closed), where I had a similar idea.
Interesting! Do you think this more limited approach (just giving a stylesheet to a custom element) is sufficient, or do you still think we need the ability to target arbitrary elements with a compound selector? I can see arguments either way.
(I think we need this current idea either way; providing default styles for a component is good and useful all by itself.)
Interesting! Do you think this more limited approach (just giving a stylesheet to a custom element) is sufficient, or do you still think we need the ability to target arbitrary elements with a compound selector? I can see arguments either way.
It looks that each solves the different use cases. If a selector used in "a stylesheet to a custom element" always has a ":host" pseudo class, both approaches might be able to address the original concern.
If we can assume that ":host" is always used in a selector here, can we have a more lightweight approach?
e.g.
In default, a style only applies to the custom element itself.
That means "*" only matches the custom element itself in this context.
Allow only a compound selector to avoid the wrong usage.
e.g. "div > *" is invalid.
customElements.define("cool-element",CoolElement,{style: "* {display: block; } *[red=true] {color: red; }",shadowtreestyle: ... /* if we still need this */});
Thus, I would like to limit more and more so that it can become style-engine friendly, ignoring a shadow tree in most cases.
That sounds reasonable to me! I think I agree that if you want to style the custom element's contents more fully, you should probably be using a shadow tree. The behavior of styles in shadow trees already works pretty well.
So this brings your idea from #376 fully in line with the idea from this thread; the {style: "..."} option just provides a convenient inline mechanism for defining such styles on the element, without having to repeat the tagname over and over if you're defining multiple selectors. We can then lean on your @global-compound-selector-rule (with a better name, of course ^_^) for the declarative side of things, or if people want to provide the styles in their CSS file rather than in their JS file. (And we can do it in the future; no need to block this thread's idea on figuring out the details of the CSS rule.)
From the conference: There's no real objection to this proposal, but it needs to be more worked out with respect to the CSS cascade and such before it can be properly reviewed. Another concern that was raised is that it would help if there was some kind of holistic overview to styling custom elements and shadow DOM since there appear to be several overlapping approaches.
holistic overview to styling custom elements and shadow DOM since there appear to be several overlapping approaches.
That makes sense. Here the scenarios we've run into so far that need styling:
Custom elements need some equivalent of "user agent styling", to set up how they look by default; at minimum, they need to be able to set display so the page doesn't render totally screwed up. Preferably this should be possible without requiring a shadow root. This must apply thru shadows; that is, it can't be done by a global stylesheet just applying a x-foo {...} style.
Custom elements with shadows need a way to style all of their contents.
Authors using custom elements need a way to style them.
Maybe need some way to style all instances of a particular element in the page the same way? Like make all buttons look the same.
#1 is this proposal - attach some styles to the element at registration time, they're treated as user-agent origin.
Again, I can't emphasize enough our objection for using a new cascading order.
This feature was originally proposed as a way of avoiding the performance penalty to have a shadow root. Introducing a new cascading order would totally defeat that performance benefit by introducing more complexity and performance cost in our implementation.
In general, this issue has morphed into a feature which lacks a clear list of use cases and instead of a solution looking for use cases to back that up. We need to re-enumerate a clear list of concrete use cases this feature is supposed to address since the proposed solution and the original problem make no sense whatsoever at this point.
Is there any real benefit to this feature over just pushing a sheet into document.adoptedStyleSheets (assuming that feature gets finalized and adopted)? If not, why not just defer to that proposal? Ostensibly the best way to create an otherwise inert stylesheet would be using the features already being discussed around adoptedStyleSheets.
EDIT
Could this be sugar for adoptedStyleSheets that would push the host styles into whatever DocumentOrShadowRoot a given element becomes connected in? Not sure how the resolution would work not knowing tag names unless there's some magic involved. Just thinking out loud.
Thanks.
Style rules added in document.adoptedStyleSheets are only applied to an element in a document tree.
Custom elements in other trees, e.g. shadow trees, wouldn't get styled.
We have to add style rules to every node trees' adoptedStyleSheets, which is impractical, I think. The author of custom elements can't control how they are used and where they are used. If the user of custom elements forget to add style rules to some node tree's adoptedStyleSheets, the custom element in the tree wouldn't get styled.
But then the author of a component can't specify !important rules for things like display without which the component may not function. This is a deal break for us.
Could you clarify the use case for a component author overriding display and other rules? It is unthinkable to me that a component consumer should be blocked from using display: none.
But then the author of a component can't specify !important rules for things like display without which the component may not function. This is a deal break for us.
Could you clarify the use case for a component author overriding display and other rules? It is unthinkable to me that a component consumer should be blocked from using display: none.
For example, some components may not function when display is inline because it assumes the block layout to be happening in its shadow tree. As another example, certain component may not support vertical writing mode. e.g. input, textarea, etc... don't automatically inherit its parent writing mode; in that case, being able to force a horizontal writing mode on the component's shadow tree is crucial.
I suppose the writing-mode example makes sense, but I feel like !important is not the correct mechanism for this kind of thing. If I add display: inline to a <textarea> element, it's true that this style will be ignored and the computed style will be inline-block, but I can still use display: none, which is an age-old method of hiding elements and preventing them from affecting layout.
Generally, I think it's going to be very unusual to attach a shadow root to an element you don't define.
All of my custom elements except for one, have styles but no shadow roots and do not distribute any children. Currently I'm applying styles using JSS directly to all of their style="" attributes (because otherwise they don't reach into shadow roots).
Applying these styles via the custom element definition would be great!
Now that I think about it, I think something like a static stylesheet property in the element's class definition would be nicer, and makes more sense when thinking about which styles a custom element class inherits from a parent class (f.e. it makes sense that classes extending HTMLDivElement would have display: block by default, while classes extending HTMLSpanElement would have display: inline by default).
@rniwa in order to solve the override problem, what if a new CSS function were introduced to allow an author to define permitted styles for an element? e.g.
:host{display:allow(block, inline-block, none);writing-mode:allow(horizontal-tb);/* special interaction with minmax() ? */--column-width:allow(minmax(10px,300px));}
The function could be special-cased to only be valid in the UA origin (to be compatible with @tabatkins's suggestion of making the styles work like UA defaults), but override even !important declarations where the property is not one of the permitted values. The first value in the list would be the default.
This way, you don't need a new stacking order and you can define a subset of permitted values for the props that matter. It would also provide reasoning for UA elements that behave this way already, such as setting display: inline on a <textarea> as I mentioned before, and would improve tooling by, for example, only showing those permitted values when interacting with the properties in the dev tools.
@sorvell FYI I downvoted your original post not because I don't like the idea, but because I think that passing class-specific stuff into a non-class API seems funky. Seems like we should take advantage of mechanisms that class provides because we're using it (re: my previous comment).
I think it would be cool to give us the option to include multiple stylesheets on a web component.
I can imagine a usecase where someone would want to include a css library + some custom rules on his web component. Lets say I create a web-component library and I want to use bootstrap + my own project-wide stylesheet.
@alkismavridis that's possible via the ShadowRoot.adoptedStyleSheets property in Blink, or whatever replaces it when Safari and FF implement (it'll be a bit different).
@justinfagnani is there a resource/link where the successor or changes to adoptedStyleSheets are discussed? we also use it heavily in our code and I want to stay up to date :)
Activity
domenic commentedon Mar 29, 2016
I like this idea a lot. One thing about it that it solves is the issue of wanting to supply a "UA stylesheet" for your custom elements. You can't just do something like
my-element { display: block; }because this fails to reach inside shadow roots. When we had deep, you could do something likemy-element, * /deep/ my-element { display: block; }, but deep is gone. Also, that formulation is higher priority than the UA stylesheet, as noted in HTML as Custom Elements. (In particular, something like* { display: inline; }should override this "UA stylesheet level" stuff.)One thing I am still confused on is whether
:hostis the right name for the selector targeting the specific element being defined. Since we're specifically not talking about inserting a shadow root, and:hostis currently defined in terms of shadow DOM, it seems like a bad match to me, and I'd expect something new, more like:element. But others have told me:hostis a good idea. If we sufficiently redefined:hostas such (@tabatkins, @hayatoito?) then maybe it's OK. I'd still like to understand why we'd do that though.tabatkins commentedon Mar 29, 2016
+1 from me on this idea; I'd wondered about an author-controlled "UA styles" a few years ago, early in the project, and this API surface feels good, better than whatever else I'd come up with.
I presume that the selectors are meant to be interpreted "like" a shadow stylesheet, right? So they only apply to the element and its contents, and don't leak out to the global level? In that case this is pretty easy - just need to specify that the styles are interpreted in the user-agent origin and all of its selectors are scope-contained by the host element.
I think using
:hostis fine - it has a very similar meaning here to what it does in shadow DOM, and that makes things easier to understand. Do we plan to "hide" the host element, like you get in real shadow DOM? (I think we should, to keep the similarities as high as possible.) If so, then we just need to additionally say that, for the purposes of these selectors, the root element is featureless and matches:host/:host()/:host-context(). (This is more-specific-overriding-general, contradicting the general rule that:host/etc represents nothing outside a shadow tree.)Question: do we want to necessarily tie this to the registerElement() call? Or do we want to allow embedding this into your global CSS too, so that even if your JS is slow or broken, your page at least doesn't totally break? We'd put it under a
@custom-element foo-bar {...}rule or something similar. We'd just need to define an ordering for the JS sheet vs the CSS ones; I suspect the JS sheet should come afterwards, so they'll win in case of conflict.hayatoito commentedon Mar 30, 2016
See also #376 (closed), where I had a similar idea.
andyearnshaw commentedon Mar 30, 2016
I really like this idea too, though it might be worth having a custom element-specific stylesheet instead:
This way you can retain a reference and add to, remove or modify the css rules in a familiar manner later if required.
tabatkins commentedon Mar 30, 2016
Yeah, having the IDL be
(DOMString or CSSStyleSheet)would be good. Don't want to require the object-creation dance if it's something simple.tabatkins commentedon Mar 30, 2016
Interesting! Do you think this more limited approach (just giving a stylesheet to a custom element) is sufficient, or do you still think we need the ability to target arbitrary elements with a compound selector? I can see arguments either way.
(I think we need this current idea either way; providing default styles for a component is good and useful all by itself.)
hayatoito commentedon Mar 31, 2016
It looks that each solves the different use cases. If a selector used in "a stylesheet to a custom element" always has a ":host" pseudo class, both approaches might be able to address the original concern.
If we can assume that ":host" is always used in a selector here, can we have a more lightweight approach?
e.g.
Thus, I would like to limit more and more so that it can become style-engine friendly, ignoring a shadow tree in most cases.
tabatkins commentedon Mar 31, 2016
That sounds reasonable to me! I think I agree that if you want to style the custom element's contents more fully, you should probably be using a shadow tree. The behavior of styles in shadow trees already works pretty well.
So this brings your idea from #376 fully in line with the idea from this thread; the
{style: "..."}option just provides a convenient inline mechanism for defining such styles on the element, without having to repeat the tagname over and over if you're defining multiple selectors. We can then lean on your@global-compound-selector-rule(with a better name, of course ^_^) for the declarative side of things, or if people want to provide the styles in their CSS file rather than in their JS file. (And we can do it in the future; no need to block this thread's idea on figuring out the details of the CSS rule.)hayatoito commentedon Apr 1, 2016
Yeah, I do not have an intention to block this thread's idea. I'm totally fine to let
customElement.definetake a style option.annevk commentedon Apr 6, 2016
From the conference: There's no real objection to this proposal, but it needs to be more worked out with respect to the CSS cascade and such before it can be properly reviewed. Another concern that was raised is that it would help if there was some kind of holistic overview to styling custom elements and shadow DOM since there appear to be several overlapping approaches.
tabatkins commentedon Apr 6, 2016
That makes sense. Here the scenarios we've run into so far that need styling:
displayso the page doesn't render totally screwed up. Preferably this should be possible without requiring a shadow root. This must apply thru shadows; that is, it can't be done by a global stylesheet just applying ax-foo {...}style.#1 is this proposal - attach some styles to the element at registration time, they're treated as user-agent origin.
#2 is stylesheets in the shadow root.
#3 is custom properties, applied via var() and @apply.
#4 I'm not sure about yet, but Hayato's idea addresses it.
rniwa commentedon Apr 6, 2016
Which idea of Hayato are you referring for (4)?
205 remaining items
rniwa commentedon Nov 6, 2018
Again, I can't emphasize enough our objection for using a new cascading order.
This feature was originally proposed as a way of avoiding the performance penalty to have a shadow root. Introducing a new cascading order would totally defeat that performance benefit by introducing more complexity and performance cost in our implementation.
In general, this issue has morphed into a feature which lacks a clear list of use cases and instead of a solution looking for use cases to back that up. We need to re-enumerate a clear list of concrete use cases this feature is supposed to address since the proposed solution and the original problem make no sense whatsoever at this point.
calebdwilliams commentedon Nov 6, 2018
Is there any real benefit to this feature over just pushing a sheet into
document.adoptedStyleSheets(assuming that feature gets finalized and adopted)? If not, why not just defer to that proposal? Ostensibly the best way to create an otherwise inert stylesheet would be using the features already being discussed aroundadoptedStyleSheets.EDIT
Could this be sugar for
adoptedStyleSheetsthat would push the host styles into whateverDocumentOrShadowRoota given element becomes connected in? Not sure how the resolution would work not knowing tag names unless there's some magic involved. Just thinking out loud.hayatoito commentedon Nov 7, 2018
Thanks.
Style rules added in
document.adoptedStyleSheetsare only applied to an element in a document tree.Custom elements in other trees, e.g. shadow trees, wouldn't get styled.
We have to add style rules to every node trees'
adoptedStyleSheets, which is impractical, I think. The author of custom elements can't control how they are used and where they are used. If the user of custom elements forget to add style rules to some node tree'sadoptedStyleSheets, the custom element in the tree wouldn't get styled.For the latter part, #769 could be related.
andyearnshaw commentedon Nov 28, 2018
@rniwa
Could you clarify the use case for a component author overriding
displayand other rules? It is unthinkable to me that a component consumer should be blocked from usingdisplay: none.rniwa commentedon Nov 28, 2018
For example, some components may not function when
displayisinlinebecause it assumes the block layout to be happening in its shadow tree. As another example, certain component may not support vertical writing mode. e.g. input, textarea, etc... don't automatically inherit its parent writing mode; in that case, being able to force a horizontal writing mode on the component's shadow tree is crucial.andyearnshaw commentedon Nov 29, 2018
I suppose the
writing-modeexample makes sense, but I feel like!importantis not the correct mechanism for this kind of thing. If I adddisplay: inlineto a<textarea>element, it's true that this style will be ignored and the computed style will beinline-block, but I can still usedisplay: none, which is an age-old method of hiding elements and preventing them from affecting layout.trusktr commentedon Jan 23, 2019
@JanMiksovsky
All of my custom elements except for one, have styles but no shadow roots and do not distribute any children. Currently I'm applying styles using JSS directly to all of their
style=""attributes (because otherwise they don't reach into shadow roots).Applying these styles via the custom element definition would be great!
trusktr commentedon Jan 28, 2019
Now that I think about it, I think something like a
static stylesheetproperty in the element'sclassdefinition would be nicer, and makes more sense when thinking about which styles a custom element class inherits from a parent class (f.e. it makes sense that classes extendingHTMLDivElementwould havedisplay: blockby default, while classes extendingHTMLSpanElementwould havedisplay: inlineby default).andyearnshaw commentedon Jan 28, 2019
@rniwa in order to solve the override problem, what if a new CSS function were introduced to allow an author to define permitted styles for an element? e.g.
The function could be special-cased to only be valid in the UA origin (to be compatible with @tabatkins's suggestion of making the styles work like UA defaults), but override even
!importantdeclarations where the property is not one of the permitted values. The first value in the list would be the default.This way, you don't need a new stacking order and you can define a subset of permitted values for the props that matter. It would also provide reasoning for UA elements that behave this way already, such as setting
display: inlineon a<textarea>as I mentioned before, and would improve tooling by, for example, only showing those permitted values when interacting with the properties in the dev tools.trusktr commentedon Feb 1, 2019
@sorvell FYI I downvoted your original post not because I don't like the idea, but because I think that passing class-specific stuff into a non-
classAPI seems funky. Seems like we should take advantage of mechanisms thatclassprovides because we're using it (re: my previous comment).alkismavridis commentedon Jan 17, 2020
I think it would be cool to give us the option to include multiple stylesheets on a web component.
I can imagine a usecase where someone would want to include a css library + some custom rules on his web component. Lets say I create a web-component library and I want to use bootstrap + my own project-wide stylesheet.
justinfagnani commentedon Jan 17, 2020
@alkismavridis that's possible via the
ShadowRoot.adoptedStyleSheetsproperty in Blink, or whatever replaces it when Safari and FF implement (it'll be a bit different).mzeiher commentedon Jan 20, 2020
@justinfagnani is there a resource/link where the successor or changes to adoptedStyleSheets are discussed? we also use it heavily in our code and I want to stay up to date :)
web-padawan commentedon Jan 23, 2020
@mzeiher FYI, there is a recent update here WICG/construct-stylesheets#45 (comment)