What is the utility of: host,: host() and: host-context()

What is the utility of pseudo classes :host, :host() and :host-context()? If possible with some practical example

Author: Costamilam, 2018-06-22

1 answers

The pseudo-classes :host, :host() and :host-context() are part of the CSS scoping Module Level 1 specification, which are used as element selectors defined within the shadow DOM.

As a result, they only work within shadow DOM. Therefore, an example of a custom element will be used to create a Shadow DOM , and demonstrate the use of these selectors:

class Guilhermento extends HTMLElement {
  constructor() {
    super();
    let style = document.createElement('style');
    let span = document.createElement('span');
    span.textContent = 'sou filho do';

    const shadowRoot = this.attachShadow({
      mode: 'open'
    });
    shadowRoot.appendChild(style);
    shadowRoot.appendChild(span);

    style.textContent = `
      span:hover {
        text-decoration: underline;
      } 

      :host-context(div):after {
        content: "  div";
      }

      :host-context(span):after {
        content: "  span"; 
      }

      :host-context(div,span) {
        color: blue;
      }

      :host-context(.mudacor){ 
        color: green;
      }

      :host(.mudacor) { 
        color : red; 
      }

      :host {
        background: rgba(0, 0, 0, 0.1); 
      }
    `;
  }
}

window.customElements.define('gui-lher-me', Guilhermento);
<div>
  <gui-lher-me></gui-lher-me> azul
</div>

<div class="mudacor">
  <gui-lher-me></gui-lher-me> verde
</div>

<span>
  <gui-lher-me></gui-lher-me> azul
</span>

<p>
  <gui-lher-me class="mudacor"></gui-lher-me> vermelho
</p>

The selector : host , selects the root node Shadow DOM, which in the case can be represented by <gui-lher-me>. In the example he is responsible for changing the color of the background.

The selector : host(), selects the shadow DOM root node, which meets the specified requirements. In the example he is responsible for changing the text color to red.

The selector : host-context(), selects the shadow DOM root node that has the parent element, which meets the specified requirements. In the example he is responsible for change the text color to blue or green, and add additional texts.

Note: the specification is a bit more complicated than I explained earlier. The shadow DOM root node is called in the host node specification, which is the root node after the browser injects the shadow DOM into the custom element within the document DOM (i.e., after joining the shadow DOM with the document DOM).

What is the utility of pseudo classes... ?

Answer: makes it easy to define rules that affect Shadow DOM elements. Mostly rules that depend on the parent & child relationship.

 7
Author: Marcos Zolnowski, 2018-07-07 01:00:11