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

5

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

    
asked by anonymous 22.06.2018 / 20:18

1 answer

4

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

As a result, they only work inside the DOM shadow. So we'll use an example of a custom element 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 of the shadow DOM, which in this case can be represented by <gui-lher-me> . In the example it is responsible for changing the background color.

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

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

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

  

What is the use of pseudo-classes ...?

Response: Makes it easier to define rules that affect DOM shadow elements. Primarily rules that depend on the parent & child.

    
04.07.2018 / 02:00