经过我的测试,直接使用嵌套编写css是有效的,但在WebComponent中,使用:host选择器嵌套后无效。以下是演示代码,我的Chrome版本号是117
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="/index.js" type="module"></script>
</head>
<body>
<template class="template_testCom">
<style>
:host {
width: 200px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-weight: 700;
background-color: #c00;
& .container {
display: flex;
width: 100%;
height: 70%;
background-color: #fcf;
& .text {
color: #fff;
}
}
}
</style>
<div class="container">
<span class="text">textContent</span>
</div>
</template>
</body>
</html>
index.js
import TestCom from "/TestCom.js";
window.customElements.define("test-com", TestCom);
const com_testCom = new TestCom();
document.body.append(com_testCom);
TestCom.js
class TestCom extends HTMLElement {
constructor() {
super();
this.#init();
}
#init() {
const shadowRoot = this.attachShadow({ mode: "open" });
const ele_templateTestCom = document.querySelector(".template_testCom");
const content = ele_templateTestCom.content.cloneNode(true);
shadowRoot.appendChild(content);
}
}
export default TestCom;
以下是测试,当非WebComponent使用CSS嵌套时,CSS嵌套内的样式都正常使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.noWebComponent {
width: 200px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
font-weight: 700;
background-color: #c00;
& .container {
display: flex;
width: 100%;
height: 70%;
background-color: #fcf;
& .text {
color: #fff;
}
}
}
</style>
</head>
<body>
<div class="noWebComponent">
<div class="container">
<span class="text">textContent</span>
</div>
</div>
</body>
</html>
您的嵌套 CSS 不是无效。
:host
可以styleshadowDOM,但是`:host`` references组件本身,而不是内部的shadowDOM
因此,适合您的非 Web 组件代码应该以 1:1 的比例复制到 ShadowDOM,以将 CSS 应用于 DOM 节点insideshadowDOM
<style id="NESTEDSTYLE">
.wrapper {
width: 200px; height: 50px;
display: flex; justify-content: center; align-items: center;
font-weight: 700;
background-color: brown;
& .container {
background-color: grey;
& .text {
color: gold;
}
}
}
</style>
<b>DOM, no shadowRoot:</b>
<div class="wrapper" id="WRAPPER">
<div class="container">
<span class="text">textContent</span>
</div>
</div>
<script>
customElements.define("text-component", class extends HTMLElement {
constructor() {
super()
.attachShadow({mode: "open"})
.innerHTML = `<style>${NESTEDSTYLE.innerHTML}</style>` + WRAPPER.outerHTML;
}
});
</script>
<b>Web Component:</b>
<text-component></text-component>