Hacker News new | past | comments | ask | show | jobs | submit login

The main problem with the Shadow DOM which makes people avoid it is the inability to use CSS externally to style the elements which are generated internally by the component...

This is unfortunate because the Shadow DOM is essential if you want to work with child components slotted into it from the outside. This opens up many use cases.

There is one alternative which is not being considered; it's possible for components with a shadow DOM to inject their elements into the Light DOM (where they can be styled/skinned externally with CSS), you just have to make the user slot a div (or other element) from the outside to act as a 'viewport' so that the component can inject its children into it (instead of injecting them into its Shadow DOM).

With this approach, you can still access slotted elements. It's an ideal pattern for situations where you want the component to generate child elements from a slotted template.

I wrote an article about this approach here: https://dev.to/jondubois/web-components-the-template-viewpor...




This is a great approach for components that want to inherit all styling from their context.

In cases where you want to introduce just a little styling, the CSS Parts API is really cool: https://developer.mozilla.org/en-US/docs/Web/CSS/::part


Thanks for pointing this out. I should probably mention this approach in my article for cases when you need to work with slotted elements but don't want to inherit all page styles.


Cool solution. I'm using Lit, and implemented a different approach to this problem. I created a way to easily apply a set of styles to particular components, by using a mixin class:

const myStyles = litStyle(css`h1 { color: red; }`);

class MyComponent extends myStyles(LitElement) { // ..}

You can store the style definition in a separate file and import it and use it for the components that you want it for.

https://github.com/gitaarik/lit-style


Is there a comparison between light and shadow dom for webcomponents? I kinda want the simplicity of applying light dom css. Svelte doesnt support slots in light dom, I want to know the other caveats of light dom.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: