I'm trying to style the text in the shadow dom without success. The only thing is that I want to do it from outside the shadow DOM. An other important thing, the Shadow dom styling should only apply to the shadow dom inside a 'bar' element. Here is my test code:
<!doctype html>
<html>
<head>
<style>
:host(bar) span:first-child {
text-transform: uppercase;
color: green;
}
</style>
</head>
<body>
<bar></bar>
<script>
var bar = document.querySelector('bar');
var root = bar.createShadowRoot();
root.innerHTML = '<span>bar</span><span>foo</span>';
</script>
</body>
</html>
And a bonus question, what exactly does
:host(bar:host) { ... }
do ?
Shadow DOM permits encapsulation of styling rules for custom elements. You can freely define styling information for your elements, such as fonts, text colors, and classes, without fear of the styles applying outside the scope of your element.
The :host selector allows to select the shadow host (the element containing the shadow tree).
You won't be able to access the shadow DOM from the outside, If you attach a shadow root to a custom element with mode: closed set. We can only access the shadow DOM by the reference returned by attachShadow and it is probably hidden inside a class. Browser-native shadow trees are closed. There's no way to access them.
The shadow DOM specification is currently still in development, most of its functionality is radically changing from one moment to the next.
To style a shadow DOM element from the outside it depends on if your browser relies on the (outdated) peusdo-element exposure or the new css shadow dom selectors ^^
(cat) and ^
(hat)
If the browser supports the new syntax, you can simply enter an elements shadow dom using the hat (^
) selector, or if you wish to cross all shadow boundaries, you can use the cat (^^
) selector to do so.
If the browser does not yet support it, you need to expose the element you wish to style as a pseudo-element of its parent by adding the pseudo attribute to it, <shadow-element peusdo="myname" />
, and then reference that pseudo element in your css shadow-host::myname
As to your 'bonus' question, you are referencing the shadow host element, but only if the shadow host is a <bar>
element, if you omit the second :host
you are referencing a shadow host that is a <bar>
element or has one as its ancestor.
Do note that because the API is in constant development, the above information may not remain reliable beyond more then a month or so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With