WebComponent中:host选择器嵌套CSS失效问题咨询(Chrome 117)
WebComponent中:host结合CSS嵌套样式失效问题
经测试,普通场景下直接使用CSS嵌套语法可正常生效,但在WebComponent中结合:host选择器进行CSS嵌套时样式失效,测试使用Chrome版本为117。
复现Demo代码
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仅显示:host定义的红色背景,.container的粉色背景和.text的白色文字样式均未生效。
普通非WebComponent场景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>
效果说明:所有嵌套样式正常生效,红色背景的容器内显示粉色背景的子容器,文字为白色。
内容的提问来源于stack exchange,提问作者WZDDL
相关产品推荐
相关产品推荐

