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
Allowing CSS combinators postfixed to the ::slotted() or :host selectors #889
Borrowing some ideas from #883, I think it would be great to allow combinators after ::slotted(whatever), for example ::slotted(.foo) .bar > .lorem + ip-sum. Similarly, the previous selector would be effectively the same as :host > .foo .bar > .lorem + ip-sum for styling purposes, but :host also does not allow combinators to be appended to it.
Here's a live example showing that it currently doesn't work:
On the same token, being able to use these selectors in querySelector and querySelectorAll would be very convenient.
Here's a live example that shows that querySelector('::slotted(.foo)') doesn't work despite being a valid selector, and also showing that postfixed combinators throw an error:
Having these features as expansions on the current spec would allow what the OP in #883 asks for: it would make it very easy to style the input tree that a custom element end user provides.
There are currently complicated ways to achieve this (see comments below).
Reacted by Lonnie Best, Xianqiao Wang, Leon Heess and Sasha Firsov
changed the title [-]llow CSS combinators postfized to the ::slotted() selector[/-][+]Allowing CSS combinators postfixed to the ::slotted() selector[/+]on Jul 12, 2020
What does the ::slotted syntax add that the querySelector("[slot].foo") would not cover? Slotted content is light DOM so you shouldn't need to run that query inside shadowRoot.
Wouldn’t querySelector('::slotted(.foo)') give away that a shadow DOM exists (even in a case where the shadow root is closed)? It seems to me like host.querySelector('.foo') should suffice from a DOM API perspective although I agree the CSS selector from within a shadow root would be a nice addition if the performance worked out.
@castastrophe Thanks for that question! It's not quite what I'm asking about though.
The `::slotted` selector runs within a shadow root context (f.e. in a shadow root `querySelector`, or in a shadow root's `<style>` element), but this is already expected behavior. More details (click here to expand)...
constroot=this.attachShadow(...)// 'this' is a custom elementroot.innerHTML=html`<style>::slotted(.foo){...}</style><slot></slot>`
The ::slotted(.foo) selector in this example is in fact still an implementation detail encapsulated inside the (custom element's) shadow root.
The [slot].foo selector does a similar thing, but does it from the outside of the custom element (i.e. outside of the shadow root), so it is a tool used on the outside of a custom element's internal shadow tree by an end user of the custom element.
The custom element itself could in fact run this code internally: this.querySelector('[slot].foo'), but the style of the shadow root actually can't contain such a selector as it would not select anything. For example, this won't work on the inside of a custom element:
because it will not select nodes from the light tree that have been "slotted" into the shadow root; instead it will select nodes that are within the shadow root's own DOM that have a slot="" attribute (and in that example there aren't any).
In other words, calling this.querySelector('[slot].foo .bar') on a custom element selects any elements in the light tree with a slot attribute even if they are not actually slotted.
So inside of a custom element's implementation (in its shadow root), the ::slotted(.foo) selector is useful for selecting actually-slotted elements from the light tree, which is something that only the custom element (its shadow root) would care about (otherwise, as @calebdwilliams mentioned, the user would be aware of the shadow root's existence if they could run that selector on the custom element instead of on the custom element's (possibly closed and invisible) shadow root).
END DETAILS
Anywho, all of the aforementioned is already an existing concept.
The main ask of the OP is to be able to take a selector like ::slotted(.foo) (which already works, within a shadow root) and to be able to append combinators to it. For example ::slotted(.foo) .bar or ::slotted(.foo) > .bar.
As an example, try running the following in your console (tested in Chrome).
What you'll notice is that the square will be colored deeppink, but the expected result is for the square to be cyan.
The reason is because the ::slotted(.foo) selector is working fine, but the ::slotted(.foo) .bar selector doesn't do anything (unlike what we may expect).
That is not to say that is not a valuable conversation to have - whether or not a component should be able to style more than just top-level nodes inside a slot - but I do think it's a different topic than the title and description here imply.
That is not to say that is not a valuable conversation to have - whether or not a component should be able to style more than just top-level nodes inside a slot
Continue the conversation with its full history, that started 5 years ago, and resulted in V1 ::slotted only taking a simple selector,
because ::content and <content> in V0 (allowed for complex selectors, never implemented in FireFox & Safari) did not perform.
Thank you for the links. I am aware of the current spec. Five years is a long time in tech and specs are not immutable. As efficiency is improved, new options may be available. I also was not implying the conversation should be_started_, but pointing out on this thread that it's a different conversation than this one.
FWIW, if complex slotted light dom selectors were permitted, I'd expect the selector in the examples above to be ::slotted(.foo .bar), not ::slotted(.foo) .bar. The latter seems to describe a slotted light dom element ".foo" with a descendent shadow element ".bar". Since that scenario can't seemingly occur, the problem might not be obvious ... but switch to just about any other combinator and you get a scenario that can occur (e.g. ::slotted(.foo) + .bar - "style the shadow .bar when preceded by a slot with an assignee matching .foo").
AFAIK, selectors like this are also not currently permitted, but I'm unsure if that's a matter of deliberate design or not; they still seem to adhere to query-direct-assignees-only.
Edit:
Thinking about this further, I guess + ... also would never match, given the slot itself is "in the way" - the assignee is not a sibling. So perhaps this distinction doesn't matter, at least so long as CSS continues to have no "backwards" selectors.
but I do think it's a different topic than the title and description here imply.
@castastrophe Did you mean the title I chose doesn't match what I proposed in the OP? If so, in my mind I think it matches because it says "combinators postfixed to the ::slotted() selector", and then I am describing what I believe would be intuitive for that to do.
FWIW, if complex slotted light dom selectors were permitted, I'd expect the selector in the examples above to be ::slotted(.foo .bar), not ::slotted(.foo) .bar. The latter seems to describe a slotted light dom element ".foo" with a descendent shadow element ".bar".
@bathos That is not intuitive because it is impossible. Why would someone be thinking that, when it doesn't exist?
That's like if I said .foo > .bar should select any .foo elements that have greater amount of text content than the .bar element with largest amount of text. But I'd be making things up at that point.
I think a better interpretation is this:
::slotted(.foo .bar) represents an element in the light tree that matches .foo .bar in the light tree (it is a descendant of a .foo element anywhere in that light tree). I think that's intuitive.
::slotted(.foo) .bar represents the .bar element that happens to be a descendant of a slotted .foo element. This is also intuitive.
I guess + ... also would never match,
If we think intuitively about this, then: a selector like ::slotted(.foo) + .bar would style a .bar element that happens to be the "adjacent sibling" of a .foo element where the .foo element is a slotted element. This is intuitive.
Note that the .bar element could very well be distributed to an entirely different slot (but still have the styling specified for that selector). That makes intuitive sense and could be totally useful.
@Danny-Engelman, @hayatoito's comment you screenshotted shows no performance metrics. I am not a browser developer, but I very much doubt (I could be wrong) that ::slotted(.foo) .bar could really be so slow that it matters for the vast majority of use cases.
What I mean is, there's plenty of ways to make really slow selectors in regular DOM, without any shadow DOM even existing. We should not throw out an idea based on a single thought that said it would be slow without any viable data.
What if I said "multi-pass WebGL rendering is slower than single-pass rendering, so we should throw out multi-pass APIs".
But in fact, multi-pass rendering can be very useful when the performance implications fit within given constraints.
It would be great to give web developers useful selectors, and then explain to them that they should avoid re-running these selectors repeatedly; but that it is fine if the cost fits within performance requirements for the application.
I feel that we're prematurely optimizing here. However I know that the web APIs can't be reversed (though I've been imagining how to do that without breaking the web).
Every single DOM API that exists can technically be slooow if we examine it within the context of a particular use case that happens to be the worst use case where we'd never want to perform the given action in the way it is performed.
The following would not be ideal (if selectors like ::slotted(.foo) .bar were supported) unless the use case still fits withing some given performance requirements:
The following may be much better (if the selector were supported) for a use case in which the functionality works as intended:
connectedCallback(){constel=this.shadowRoot.querySelector('::slotted(.foo) .bar + .baz')requestAnimationFrame(functionloop(t){// does not re-run the selector every time:el.style.transform=`rotateY(${10*Math.sin(t*0.001)}deg)`requestAnimationFrame(loop)})}
@hayatoito (and @emilio from the other thread) Can you please expand on the performance issues, and provide useful metrics that we can reference here?
Cool. So basically what you are saying is slot > div span (inside a shadow root style) achieves the same as the hypothetical concept ::slotted(div) span (in a shadow root style) of the OP!
(You could've simply just said that.)
A hypothetical ::slotted(div[slot="foo"]) span is the same as slot[name="foo"] > div span.
Works great! For some reason I hadn't thought of it.
Side note: performance of the hypothetical ::slotted(div) span can and should in theory be the same as slot > div span. I still don't see how performance can be an argument against it.
This is becoming an "I think Array index should start at 1" topic
From what I can tell, this is a "There's no way to index into an array with simple notation" problem. 😄
Here's a solution that works:
// within the custom element code, inside a MutationObserver handler:this.children.forEach(child=>{if(childinstanceofHTMLParagraphElement&&child.children[0]instanceofHTMLSpanElement){child.children[0].style='background: cyan'}})
but that's like a
we can't index an array with array[index] so just write
It is still a Work-Around!! To style <slot> content from a <style> tag IN the TEMPLATE
I rewrote the code.. JS is still the same, except I changed ...this.children to ...this.childNodes to include #textnodes in the move from one lightDOM to a nested lightDOM.
Ah, ok. I see what you did, which I missed before.
It is a very bad solution because it totally obliterates the end user's tree (removes it from their DOM, and places it into an internal shadow root). This has critical issues:
The end user's light-tree styling no longer applies
for example, when the end user writes the custom element in the top level Document, and adds top-level styling in the document, this styling will not style the elements as they were expecting, because the elements have been moved into a shadow root.
The end user will have a very false sense of their tree structure. They will experience errors like this:
// `el` will be `undefined` instead of an `<h1>`constel=document.querySelector('component-with-slots').children[0]el.style.foo='bar'// runtime error!!!
The code is cryptic and difficult to understand. The end user will be forced to read the the source code to find out what happened to their tree (or the CE author would have to document the awkward behavior).
This leads to harder-to-maintain code, both for the end user, and for custom element authors.
More resource usage: two shadow roots per custom element, and extra CPU usage moving nodes every time one of the custom elements is created, etc.
I would suggest for anyone reading this, never ever write code that way. That is simply not an acceptable solution because the downsides (especially for the end user) are bigger than the benefit (namely for the CE author only).
@Danny-Engelman Unless there is some solution we've missed, you shown why clearly we need a solution, so as to avoid complicated and highly undesirable workarounds.
The most acceptable solution that I can think of right now is, to implement scoped styling:
Instead of creating an extra layer of shadow root,
write a special style handler in the custom element that attaches certain styles to the custom element's nearest root node (either a Document, or a ShadowRoot).
In those styles, style the desired elements using scoped styles (for example with UUIDs or similar) so that the styles affect only the particular elements of the custom element's light tree.
This would require setting a unique attribute (or similar) on the custom element, for example <component-with-slots library-name-style-id="12345">
The style processing mechanism inside the custom element would convert selectors like :outside span to component-with-slots[library-name-style-id="12345"] span
Or better yet, to semi-polyfill the concept of this issue's OP, it would convert ::slotted() span or :host > * span to component-with-slots[library-name-style-id="12345"] > * span.
Note, I was hoping :host > * foo would essentially be a working alternative for ::slotted() foo, but :host also does not accept combinators after it. I updated the OP to mention this too.
This approach would be much less invasive to the end user's API contract (the end user's input (light tree nodes and attributes) should ideally be left in-tact and undisturbed, because that is theirs to manipulate). The end user will most likely be unaffected by the library-name-style-id attributes added to their light tree, but at least this is a much smaller invasion of their input space.
There is no simple solution to this, as far as I can tell so far (apart from having a feature like in the OP).
changed the title [-]Allowing CSS combinators postfixed to the ::slotted() selector[/-][+]Allowing CSS combinators postfixed to the ::slotted() or :host selectors[/+]on May 19, 2021
Activity
[-]llow CSS combinators postfized to the ::slotted() selector[/-][+]Allowing CSS combinators postfixed to the ::slotted() selector[/+]trusktr commentedon Jul 12, 2020
For those reading email, sorry, I submitted the thread early without any content, and edited the original post.
castastrophe commentedon Jul 21, 2020
What does the
::slottedsyntax add that thequerySelector("[slot].foo")would not cover? Slotted content is light DOM so you shouldn't need to run that query inside shadowRoot.calebdwilliams commentedon Jul 21, 2020
Wouldn’t
querySelector('::slotted(.foo)')give away that a shadow DOM exists (even in a case where the shadow root is closed)? It seems to me likehost.querySelector('.foo')should suffice from a DOM API perspective although I agree the CSS selector from within a shadow root would be a nice addition if the performance worked out.trusktr commentedon Aug 2, 2020
@castastrophe Thanks for that question! It's not quite what I'm asking about though.
The `::slotted` selector runs within a shadow root context (f.e. in a shadow root `querySelector`, or in a shadow root's `<style>` element), but this is already expected behavior. More details (click here to expand)...
The
::slotted(.foo)selector in this example is in fact still an implementation detail encapsulated inside the (custom element's) shadow root.The
[slot].fooselector does a similar thing, but does it from the outside of the custom element (i.e. outside of the shadow root), so it is a tool used on the outside of a custom element's internal shadow tree by an end user of the custom element.The custom element itself could in fact run this code internally:
this.querySelector('[slot].foo'), but the style of the shadow root actually can't contain such a selector as it would not select anything. For example, this won't work on the inside of a custom element:because it will not select nodes from the light tree that have been "slotted" into the shadow root; instead it will select nodes that are within the shadow root's own DOM that have a
slot=""attribute (and in that example there aren't any).In other words, calling
this.querySelector('[slot].foo .bar')on a custom element selects any elements in the light tree with aslotattribute even if they are not actually slotted.So inside of a custom element's implementation (in its shadow root), the
::slotted(.foo)selector is useful for selecting actually-slotted elements from the light tree, which is something that only the custom element (its shadow root) would care about (otherwise, as @calebdwilliams mentioned, the user would be aware of the shadow root's existence if they could run that selector on the custom element instead of on the custom element's (possibly closed and invisible) shadow root).END DETAILS
Anywho, all of the aforementioned is already an existing concept.
The main ask of the OP is to be able to take a selector like
::slotted(.foo)(which already works, within a shadow root) and to be able to append combinators to it. For example::slotted(.foo) .baror::slotted(.foo) > .bar.As an example, try running the following in your console (tested in Chrome).
What you'll notice is that the square will be colored
deeppink, but the expected result is for the square to becyan.The reason is because the
::slotted(.foo)selector is working fine, but the::slotted(.foo) .barselector doesn't do anything (unlike what we may expect).Expected result:
Actual result:
Live demo
castastrophe commentedon Aug 2, 2020
Ah, thank you for the code example. This is not really about the
::slottedselectors then. This is about the fact that a web component cannot style or access any descendent greater than a direct child, top-level nodes inside slotted content. Your.barclass is nested, which is why::slottedcannot influence it. https://developers.google.com/web/fundamentals/web-components/shadowdom#slotscastastrophe commentedon Aug 2, 2020
That is not to say that is not a valuable conversation to have - whether or not a component should be able to style more than just top-level nodes inside a slot - but I do think it's a different topic than the title and description here imply.
castastrophe commentedon Aug 2, 2020
I wanted to share this codepen that plays around with a few different ways you can use slotted selectors and pseudo elements: https://codepen.io/castastrophee/pen/OJMKeKa
Danny-Engelman commentedon Aug 2, 2020
Continue the conversation with its full history, that started 5 years ago, and resulted in V1
::slottedonly taking a simple selector,because
::contentand<content>in V0 (allowed for complex selectors, never implemented in FireFox & Safari) did not perform.https://developer.mozilla.org/en-US/docs/Web/HTML/Element/content (deprecated)
( 2015 #331 ) "::slotted" pseudo elements
( 2018 #745 ) ::slotted() should full support complex selector!!
The main take away from 5 years of W3C standards discussions is:
I am not the one to disagree with a Components Lead Developer
castastrophe commentedon Aug 2, 2020
Thank you for the links. I am aware of the current spec. Five years is a long time in tech and specs are not immutable. As efficiency is improved, new options may be available. I also was not implying the conversation should be_started_, but pointing out on this thread that it's a different conversation than this one.
bathos commentedon Aug 2, 2020
FWIW, if complex slotted light dom selectors were permitted, I'd expect the selector in the examples above to be
::slotted(.foo .bar), not::slotted(.foo) .bar. The latter seems to describe a slotted light dom element ".foo" with a descendent shadow element ".bar". Since that scenario can't seemingly occur, the problem might not be obvious ... but switch to just about any other combinator and you get a scenario that can occur (e.g.::slotted(.foo) + .bar- "style the shadow.barwhen preceded by a slot with an assignee matching.foo").AFAIK, selectors like this are also not currently permitted, but I'm unsure if that's a matter of deliberate design or not; they still seem to adhere to query-direct-assignees-only.
Edit:
Thinking about this further, I guess
+ ...also would never match, given the slot itself is "in the way" - the assignee is not a sibling. So perhaps this distinction doesn't matter, at least so long as CSS continues to have no "backwards" selectors.Danny-Engelman commentedon Aug 3, 2020
If you want to track selectors (in this case
:host-context) about to be removed from the spec also read:w3c/csswg-drafts#1914
trusktr commentedon Aug 5, 2020
@castastrophe Did you mean the title I chose doesn't match what I proposed in the OP? If so, in my mind I think it matches because it says "combinators postfixed to the ::slotted() selector", and then I am describing what I believe would be intuitive for that to do.
trusktr commentedon Aug 5, 2020
@bathos That is not intuitive because it is impossible. Why would someone be thinking that, when it doesn't exist?
That's like if I said
.foo > .barshould select any.fooelements that have greater amount of text content than the.barelement with largest amount of text. But I'd be making things up at that point.I think a better interpretation is this:
::slotted(.foo .bar)represents an element in the light tree that matches.foo .barin the light tree (it is a descendant of a.fooelement anywhere in that light tree). I think that's intuitive.::slotted(.foo) .barrepresents the.barelement that happens to be a descendant of a slotted.fooelement. This is also intuitive.If we think intuitively about this, then: a selector like
::slotted(.foo) + .barwould style a.barelement that happens to be the "adjacent sibling" of a.fooelement where the.fooelement is a slotted element. This is intuitive.Note that the
.barelement could very well be distributed to an entirely different slot (but still have the styling specified for that selector). That makes intuitive sense and could be totally useful.trusktr commentedon Aug 5, 2020
@Danny-Engelman, @hayatoito's comment you screenshotted shows no performance metrics. I am not a browser developer, but I very much doubt (I could be wrong) that
::slotted(.foo) .barcould really be so slow that it matters for the vast majority of use cases.I wrote a comment about that at #745 (comment).
What I mean is, there's plenty of ways to make really slow selectors in regular DOM, without any shadow DOM even existing. We should not throw out an idea based on a single thought that said it would be slow without any viable data.
What if I said "multi-pass WebGL rendering is slower than single-pass rendering, so we should throw out multi-pass APIs".
But in fact, multi-pass rendering can be very useful when the performance implications fit within given constraints.
It would be great to give web developers useful selectors, and then explain to them that they should avoid re-running these selectors repeatedly; but that it is fine if the cost fits within performance requirements for the application.
I feel that we're prematurely optimizing here. However I know that the web APIs can't be reversed (though I've been imagining how to do that without breaking the web).
Every single DOM API that exists can technically be slooow if we examine it within the context of a particular use case that happens to be the worst use case where we'd never want to perform the given action in the way it is performed.
The following would not be ideal (if selectors like
::slotted(.foo) .barwere supported) unless the use case still fits withing some given performance requirements:The following may be much better (if the selector were supported) for a use case in which the functionality works as intended:
@hayatoito (and @emilio from the other thread) Can you please expand on the performance issues, and provide useful metrics that we can reference here?
15 remaining items
trusktr commentedon Mar 22, 2021
Cool. So basically what you are saying is
slot > div span(inside a shadow root style) achieves the same as the hypothetical concept::slotted(div) span(in a shadow root style) of the OP!(You could've simply just said that.)
A hypothetical
::slotted(div[slot="foo"]) spanis the same asslot[name="foo"] > div span.Works great! For some reason I hadn't thought of it.
Side note: performance of the hypothetical
::slotted(div) spancan and should in theory be the same asslot > div span. I still don't see how performance can be an argument against it.trusktr commentedon May 13, 2021
@Danny-Engelman Can you make a really simple example, not a super complex one? I am not having any luck with it:
https://codepen.io/trusktr/pen/e80e9d5d09de7facf22aeee85f6a7549
As you can see there, only the Shadow DOM's nodes are styled, but not the content that is "slotted".
Not sure why I thought it "worked great" before, but clearly in that example it doesn't work.
Update: I thought I could make it work with a combination of
slot > *and:host > *but apparently that doesn't work either:https://codepen.io/trusktr/pen/cf1ee41ddf779a7fb60eff121b65bc1c
It seems CSS combinators are not allowed after
:hosteither.trusktr commentedon May 13, 2021
From what I can tell, this is a "There's no way to index into an array with simple notation" problem. 😄
Here's a solution that works:
but that's like a
sort of topic, except the CSS version is uglier because it modifies the end user's public
styleAPI contract.Danny-Engelman commentedon May 17, 2021
No, I am not. It is not possible.
Slotted content is styled by its host container (global CSS if you only have 1 one element with shadowDOM)
There is no simple example. Your CodePen has one shadowRoot.
and the original
innerHTML/ lightDOM needs to be moved to shadowRoot Add index.html in the root directory to make specifications more discoverable #1ps: your CodePen is private so can't be forked
I keep the ::slotted StackOverflow answer, I posted a year ago, updated with every fact and rumor I read.
https://stackoverflow.com/questions/61626493/slotted-css-selector-for-nested-children-in-shadowdom-slot/61631668#61631668
no updates there for months.
Danny-Engelman commentedon May 17, 2021
Joe Pea aka trusktr, got me working again.
It is still a Work-Around!! To style
<slot>content from a<style>tag IN the TEMPLATEI rewrote the code.. JS is still the same, except I changed
...this.childrento...this.childNodesto include #textnodes in the move from one lightDOM to a nested lightDOM.I deleted most styling examples and comments.
Is this simple enough?
TWO shadowRoots to style
<slot>sand not bleed CSS: https://jsfiddle.net/WebComponents/rhodv143/trusktr commentedon May 19, 2021
Ah, ok. I see what you did, which I missed before.
It is a very bad solution because it totally obliterates the end user's tree (removes it from their DOM, and places it into an internal shadow root). This has critical issues:
I would suggest for anyone reading this, never ever write code that way. That is simply not an acceptable solution because the downsides (especially for the end user) are bigger than the benefit (namely for the CE author only).
@Danny-Engelman Unless there is some solution we've missed, you shown why clearly we need a solution, so as to avoid complicated and highly undesirable workarounds.
The most acceptable solution that I can think of right now is, to implement scoped styling:
<component-with-slots library-name-style-id="12345">:outside spantocomponent-with-slots[library-name-style-id="12345"] span::slotted() spanor:host > * spantocomponent-with-slots[library-name-style-id="12345"] > * span.:host > * foowould essentially be a working alternative for::slotted() foo, but:hostalso does not accept combinators after it. I updated the OP to mention this too.This approach would be much less invasive to the end user's API contract (the end user's input (light tree nodes and attributes) should ideally be left in-tact and undisturbed, because that is theirs to manipulate). The end user will most likely be unaffected by the
library-name-style-idattributes added to their light tree, but at least this is a much smaller invasion of their input space.There is no simple solution to this, as far as I can tell so far (apart from having a feature like in the OP).
[-]Allowing CSS combinators postfixed to the ::slotted() selector[/-][+]Allowing CSS combinators postfixed to the ::slotted() or :host selectors[/+]bennypowers commentedon Oct 7, 2021
See also w3c/csswg-drafts#3896
leonheess commentedon Apr 28, 2022
This is needed
trusktr commentedon Jul 29, 2022
Related: #936