Home > Mobile >  Turning the background color red using the :host selector?
Turning the background color red using the :host selector?

Time:08-16

In this enter image description here

What :host is selecting is the shadow host node in the picture. Itself has no objects in the tree.

Why no red ?

If you would use this css, you would see some weird behavior adding red stripes to the top and bottom of your page:

:host { background-color: red; padding: 10px; }

We have just given padding to an object without any context of its own. As you noticed the .background-div node under the host node remains white.

However, that is because the objects under the shadow host do not inherit the background-color.

If you would then add this:

:host {
  background-color: red;
  padding: 10px;
}
:host .background-div {
  background-color: inherit;
}

You will see that .background-div now turns red. Things like font-weight ARE inherited by objects by default, that's why :host { font-weight: bold; } does have an effect.

In short

:host is best used just to ensure encapsulation (= prevent bleed of styling in child components), not to select any object in the DOM. For this it requires a selector behind it.

CodePudding user response:

According to documentation on MDN:

The :host CSS pseudo-class selects the shadow host of the shadow DOM containing the CSS it is used inside — in other words, this allows you to select a custom element from inside its shadow DOM.

So something like

  :host {
      background-color: red;
    }

Will have no effect because it is used outside a shadow DOM.

  • Related