首页 > 解决方案 > shadow dom ::part 元素的样式子元素

问题描述

我有一个 web 组件,它在 shadow dom 中呈现以下内容:

<custom-banner>
  #shadow-root
    <div part="headertext">
      I am the header text!
    </div>
    ...
</custom-banner>

要设置 的样式headertext,以下 css 效果很好:

custom-banner::part(headertext) {
  border: 5px solid green;
}

现在说我有这样的事情:

<custom-banner>
  #shadow-root
    <div part="headertext">
      I am the header text!
      <span>I am the subheader text!</span>
    </div>
    ...
</custom-banner>

有没有办法针对阴影部分的孩子?也就是说,像这样的东西(似乎不起作用):

custom-banner::part(headertext) span {
  border: 5px solid red;
}

我意识到这种事情可能会削弱 的整个目的::part,但也许不会?

需要明确的是,在此示例中,子标题跨度不是开槽子。它始终是组件的一部分,并且位于shadow dom 中。上面的示例是在浏览器中呈现的组件。

谢谢!

标签: cssweb-componentshadow-dom

解决方案


唉,你只能设置节点本身的样式::part

不是孩子,这会破坏::part目的,
还不如允许所有来自外部的 shadowDOM 样式。(做不到

如果您不想指定 a part="subheader",则
可以使用 CSS 属性,范围part,请参阅--subheader: blue

好博客:

<style>
  body {
    /* note how 'inheritable styles' do style shadowDOM */
    font: 28px Arial;
    color: green;
  }
  custom-banner::part(headertext) {
    /* style shadowDOM from global CSS */
    background: pink;
    --subheader: blue;
  }
</style>

<custom-banner></custom-banner>

<script>
  customElements.define("custom-banner", class extends HTMLElement {
    constructor() {
      super()
        .attachShadow({mode:"open"})
        .innerHTML = `<style> span {  color:var(--subheader)  } </style>` +
                     `<div part="headertext">I am the header text!` +
                        `<span>I am the subheader text!</span>` +
                     `</div>`;
    }
  });
</script>


推荐阅读