Web Component Styles Are (mostly) Encapsulated Without Shadow DOM

Shadow DOM is often thought of as the one and only way to create scoped styles for a Web Component. It's not.

Prefixed Tags Scope Styles

Web Components, i.e. Custom Elements, require a prefixed tag.

For example, a "foo" Custom Element would be defined as x-foo. That custom tag can be used in a global stylesheet in the same way native tags are used. And because there will be no pre-existing styles matching that custom tag and HTML will never define a native tag with that same name, this tag's style is effectively scoped to each the x-foo component. No Shadow DOM is needed!

Going forward, styles for the x-foo tag will only apply to instances of the foo element. Changing x-foo color to lime green, for example, does not risk unintentionally making other elements lime green because a Custom Elements’ unique tag selector effectively scopes that CSS to the component:

/* 
  This global rule only applies to <x-foo> elements.
*/
x-foo {
  color: lime;
}

Two considerations to be aware of...

First, it is technically possible for other stylesheets to use the x-foo selector, which could potentially cause problems. This is very unlikely as Custom Element tag prefixes are part of the identity - the API - of whatever libraries you are using. For example, if your app used the Mdash library (my project btw), then you know that m- is "owned" by that library. Same for IBM's Carbon, which "owns" cds-. Using m- or cds- for your own elements is risky and wrong. Websites can have many custom element libraries from internal or external sources, so you just need to be mindful and avoid using prefixes you don't control.

Second, children of Custom Elements may inherit styles. Let's say our foo component above permits a button child. That button could potentially inherit the lime green color. This can be avoided by setting an explicit color on global button styles (very much the norm) or by defining custom styles for foo's button as part of its x-foo CSS rules.

Don't Fear Global CSS

Global CSS is not to be feared. In the past, bad practices led teams to believe the way out was through framework's and their proprietary CSS-in-JS solutions. Custom Elements, or Custom Elements with a Shadow DOM to be precise, offer the same encapsulation without the costs of those dependencies. What's even better when full on Web Components are not needed, is using the power of a prefixed custom HTML tag to quickly and easily and safely define component styles using global CSS.

You can learn more about this approach by reading TAC: A new CSS methodology.