Skip to content Skip to sidebar Skip to footer

Why Do Pseudoclasses On The Host Element Have To Be Inside Of The Host Function?

I do not understand why pseudo classes like :focus-within need to be within the :host() function brackets when acting on the host itself. Why can it not be :host:focus-within div?

Solution 1:

:host is only to indicate the host element of the shadowDOM.

:host(.something) indicated the host with a class of .something.

You can not use :host.something you must use the parenthesis.

:host() is not a function. It is just how to select a :host with additional specificity.

classMyElementextendsHTMLElement {
	constructor() {
		super();
		this.attachShadow({mode: 'open'}).innerHTML = `
		<style>
    :host{
      display: block;
      padding: 20px;
      background-color: salmon;
    }

    div{
      background-color: white;
    }

    :host(:focus-within) div{
			background-color: green;
		}
		</style>
    <input type="text" value="click in here"/>
		<div>Change to green</div>`;
	}
}
window.customElements.define('my-element', MyElement);
<my-element></my-element>

Solution 2:

Actually the reason is given in Selector Level 4 specification:

The shadow host in a shadow tree is featureless and therefore cannot be matched by any pseudo-class except for :host [...].

It is illustrated in the hyperlink in the example (and actually also the link you pointed in your comment to @Intervalia's answer).

Transposed to your use case:

:focus-within doesn't match the shadow host. So, :host:focus-within which is more specific, should/could not match anything (that would be contradictory to the CSS selection fundamental).

Hence the :host() function pseudo-class that will mimic the other selectors but won't break their logic.

Post a Comment for "Why Do Pseudoclasses On The Host Element Have To Be Inside Of The Host Function?"