Inheritance inside a shadow DOM slot

时间:2017-06-15 09:51:29

标签: css inheritance web-component shadow-dom custom-element

The spec here - https://drafts.csswg.org/css-scoping/#slots-in-shadow-tree has a note as follows.

Note: A non-obvious result of assigning elements to slots is that they inherit from the slot they’re assigned to. Their original light tree parent, and any deeper slots that their slot gets assigned to, don’t affect inheritance.

So I am thinking that once an element is slotted, the styles that gets applied to that element and can be inherited like color or background-color won't inherit from it's light DOM parent.

In the following example, however, this does.

Here's my code.

class CustomTitle extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = "<slot name='title'></slot>";
  }
}
window.customElements.define("custom-title", CustomTitle);
custom-title {
  border: 2px solid;
  display: block;
  color: red;
}
<custom-title>
  <h1 slot='title'>Hi There!</h1>  
</custom-title>

My expectation is that h1 will still be black but it shows up as red. Clearly I am not what the spec means or I am doing something silly.

Can someone please explain this to me?

1 个答案:

答案 0 :(得分:2)

Sorry, that note is meant to imply that the element inherits directly from it's first slot. Inheritance will still work as normal, from higher slots, other shadow elements, light elements that host shadow trees, etc

This example doesn't show off inheritance, tho. The h1 got a color assigned to it, so it'll just use that, and not use inheritance at all.