组合使用::slotted与::part伪元素设置自定义组件样式不生效问题咨询
问题原因
你编写的语法没有错误,该操作本身不被当前的Web Components规范支持。
规范明确限制了 ::slotted() 伪元素仅能选中被分发到插槽的元素本身,不支持在其后拼接其他Shadow DOM穿透类伪元素(包括::part()、嵌套的::slotted()),因此你写的::slotted(child-element)::part(button)选择器无法命中目标节点。
可行解决方案
方案1:全局样式声明
直接在全局作用域中指定子元素的part样式,是最简单的实现方式:
child-element::part(button) { background-color: red; }
方案2:CSS变量透传
如果需要父元素控制样式的权限隔离,可以通过CSS变量传递样式值:
- 在父元素的插槽样式中定义变量:
::slotted(child-element) { background-color: blue; padding: 10px; --child-button-bg: red; }
- 在子元素的模板样式中接收变量:
<template id="child-template"> <style> [part="button"] { background-color: var(--child-button-bg, #eee); } </style> <button part="button">Style me!</button> </template>
内容的提问来源于stack exchange,提问作者Mendy
相关产品推荐
相关产品推荐

