I have recently been learning about custom elements and Lit js. I am trying to style my components with the ::part
pseudo-selector.
This works in Firefox, but it seems not to work in Chrome.
As far as I can tell this should be supported in both. I have been able to replicate the issue in a code pen (linked below).
Should I expect this code to render a red square in Chrome?
import * as lit from "https://cdn.skypack.dev/[email protected]";
class TTest extends lit.LitElement {
static styles = lit.css`
::part(test) {
display: block;
color: red;
background-color: red;
height: 200px;
width: 200px;
}
`
render() {
return lit.html`
<div part="test">
</div>
`
}
}
customElements.define('t-test', TTest);
Firefox version: 108.0.1 (64-bit)
Chrome version: 108.0.5359.124 (Official Build) (64-bit)
OS: Arch Linux x86_64 6.1.1-arch1-1
CodePudding user response:
Looks like you found a bug
::part, a set of pseudo-elements that allow you to style inside a shadow tree,
from outside of that shadow tree.
FireFox seems to allow styling from inside the shadowTree itself
This Native Code has different output in Browsers:
<style>
wc-container ::part(redpart) {
color: yellow;
background-color: red;
}
</style>
<wc-container>
<wc-part-test> red part </wc-part-test>
</wc-container>
<wc-part-test> NOT red part </wc-part-test>
<script>
customElements.define('wc-container', class extends HTMLElement {
constructor(){
super().attachShadow({mode:"open"}).innerHTML=`<slot/>`;
}});
customElements.define('wc-part-test', class extends HTMLElement {
constructor(){
super()
.attachShadow({mode:"open"})
.innerHTML =
`<style>::part(redpart){ font:2em Arial }</style>`
`Hello <span part="redpart"><slot></slot></span> Web Component`;
}});
</script>
Firefox
Because the <style>
is inside the shadowRoot, the font
styling can be done without ::part
Chromium
Safari
Please share a link to your screenshot; or edit this answer
Conclusion
- https://github.com/fergald/docs/blob/master/explainers/css-shadow-parts-1.md
Says: "to style inside a shadow tree, from outside of that shadow tree." - Some AI that often gives inclomplete answers says:
"To summarize, the ::part pseudo-element is used to style elements within a Shadow DOM shadow tree that have a part attribute. It does not style the shadow root itself."
I can see use-cases for both behaviors, wonder what is used in the world already
I use ::part
the Chrome way