Search code examples
performanceshadow-domfast-ui

Using FAST Is there a way to apply styles to child ShadowDOM elements?


I've been working with the FAST toolkit (https://fast.design) creating my own elements that I wish to use. Part of that journey has lead me to make a Toolbar.

Been a Toolbar, I want to change the background of the buttons to be transparent (going for a look like: https://fluentsite.z22.web.core.windows.net/components/toolbar/definition. Now I could create another element, i.e. ToolbarButton that extends Button (and any other controls which need the background removed) and it'll work for my purpose. Still, it feels like something I should be able to do as it's a unique trait of the Toolbar.

I'm not sure if it's even possible, but I can't figure it out looking through the documentation and source code on GitHub.

Any advice would be appreciated.

Ref: https://github.com/microsoft/fast/issues/3548


Solution

  • This is a great question. Fortunately, shadow dom itself supports a CSS feature for exactly this scenario. You can use the ::slotted selector in the CSS for your toolbar to select particular elements that are slotted into the toolbar's slots and apply custom styles to them. So, you could target a button that is slotted into the toolbar and use that to set a css property on the button, or apply styles directly to it or its CSS parts. Here's the link to the MDN docs on this: https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

    Here's some sample css based on your scenario.

    ::slotted(fast-button) {
      --accent-fill-rest: transparent;
    }
    

    Remember, this must go into the toolbar's css to affect all fast-button elements that get slotted into the toolbar's slots.