Web 组件中的 css 边界到底是什么?
What exactly are the css boundaries in web components?
<html>
<style>
body { color: blue; }
</style>
<body>
<h1>Styles!</h1>
<p>somebody made a very broad selector</p>
<isolated-stuff></isolated-stuff>
</body>
<script>
class DemoElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>div { font-size: 24px; }</style> // I can add `color: initial` here
<div>why am i blue?</div>`;
}
}
customElements.define('isolated-stuff', DemoElement);
</script>
</html>
我很难理解style scoping for web modules。
Note that the functionality still works (although we had to querySelector through the shadowRoot), but we’ve totally lost the global styling. The Shadow DOM boundary (shadow root) prevents styling coming in or going out (sorta like an iframe).
我意识到我正在使用的文档可能不应该使用如此广泛的 body
样式。我能找到一些文档来说明为什么我的 div
中的文本是 blue 吗?
简短的回答是继承 跨越影子DOM 边界。
参见3.1. Informative Explanation of Shadow DOM。特别是它说:
... the shadow tree, when it exists, is used in the construction of the flattened element tree, which CSS uses for all purposes after Selectors (including inheritance and box construction).
这就是自定义属性(CSS 变量)可以跨越 Shadow DOM 边界的原因,如 CSS-Tricks 文章中所述。
由于颜色是继承的 属性,并且在您的示例中没有在影子树内重新分配,因此里面的文本继承了蓝色。
<html>
<style>
body { color: blue; }
</style>
<body>
<h1>Styles!</h1>
<p>somebody made a very broad selector</p>
<isolated-stuff></isolated-stuff>
</body>
<script>
class DemoElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>div { font-size: 24px; }</style> // I can add `color: initial` here
<div>why am i blue?</div>`;
}
}
customElements.define('isolated-stuff', DemoElement);
</script>
</html>
我很难理解style scoping for web modules。
Note that the functionality still works (although we had to querySelector through the shadowRoot), but we’ve totally lost the global styling. The Shadow DOM boundary (shadow root) prevents styling coming in or going out (sorta like an iframe).
我意识到我正在使用的文档可能不应该使用如此广泛的 body
样式。我能找到一些文档来说明为什么我的 div
中的文本是 blue 吗?
简短的回答是继承 跨越影子DOM 边界。
参见3.1. Informative Explanation of Shadow DOM。特别是它说:
... the shadow tree, when it exists, is used in the construction of the flattened element tree, which CSS uses for all purposes after Selectors (including inheritance and box construction).
这就是自定义属性(CSS 变量)可以跨越 Shadow DOM 边界的原因,如 CSS-Tricks 文章中所述。
由于颜色是继承的 属性,并且在您的示例中没有在影子树内重新分配,因此里面的文本继承了蓝色。