简体   繁体   中英

Why does this globally defined css rule affect styling inside of the shadow DOM?

I created an web-component with shadow mode 'open', which is used like this:

<scu-switch checked="true" value="switch1">
  <span id="scu-switch-label">Switch On</span>
</scu-switch>

and looks like this:

Html 工具按钮

Than I added the button to a webpage with the following global CSS:

  text-align: center;

and now the button style is broken:

在此处输入图像描述

When I inspect the button I can see, that the global style was applied to the span (and notice that it is not part of slot content) inside of the shadow root. 开发者工具

The shadow DOM is supposed to isolate style from the rest of the web page. Why was this text-align: center applied here, even though it was defined outside of the Shadow DOM?

One of the great features of the Shadow DOM in Web Components is that styles are encapsulated to the component - you can style your component without worrying about any specifier (id, class, etc.) conflicts or styles ' leaking out ' to other elements on the page.

This often leads to the belief that the reverse is true - that styles outside of the component won't cross the Shadow boundary and ' leak in ' to your component. However this is only partly true.

While specifiers do not leak in to your component (eg a color applied to an p element in a style rule outside of your component won't effect any p elements in your Shadow DOM, although the rule will be applied to your Light DOM, or slotted content),

inheritable styles applied to any elements containing your component will be applied to both your Shadow and Light DOM.

Source: https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM