Skip to content

:host-context(my-el) inside a <my-el> custom element matches even for a standalone <my-el> #11063

@franktopel

Description

@franktopel

What is the issue with the HTML Standard?

From what I've researched so far, there currently is no way in CSS to detect if my component is nested inside another instance of the same component.

See this codepen: https://codepen.io/connexo/pen/xbxVyMY

Code:

const css = `
:host {
  color: green; 
}
:host-context(my-el) {
  color: orange;
}
`;
const sheet = new CSSStyleSheet;
sheet.replaceSync(css);

customElements.define('my-el', class extends HTMLElement {
  #slotEl = document.createElement('slot');
  constructor() {
    super().attachShadow({ mode: 'open' }).adoptedStyleSheets = [sheet];
    this.shadowRoot.append(this.#slotEl);
  } 
});
<my-el>
  Outer my-el, this text should be green.
  <my-el>Inner my-el, this text should be orange.</my-el>
</my-el>

<br><br>

<my-el>Standalone</my-el>

Of course there is workarounds for this in JavaScript, but imo I shouldn't be forced into using JavaScript for a task that I understand is clearly the job of CSS.

Other than being able to re-use the same CSS for different tag names and differentiating, I don't see a reasonable use-case for :host-context() to ever match the :host itself.

I've also tried workarounds in CSS, none of which worked:

:host(:host-context(my-el)) { /* never applied */ }

:host-context(my-el):not(:host) { /* never applied */ }

What's the rationale behind the :host-context() being able to match itself? And what could be done to resolve the very common nesting use-case on the CSS side for this, from inside the shadowDOM?

Using regular document.adoptedStyleSheet's CSS for this is no option, since the nesting case could also occur inside a shadow root of another custom element.

I am raising this here in WhatWG/html because I'm assuming the CSS part of the custom element specification is rather located here than over at the CSSWG. If that assumption is wrong, please point me to where it belongs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions