Jacob Stamm
Jacob Stamm

Reputation: 1828

What's the difference between regular component styles and :host nested styles?

Consider the following component-level style for a component with the default view encapsulation value of ViewEncapsulation.Emulated:

:host h2 {
    color: red;
}

This will compile into the following CSS:

[_nghost-c0] h2[_ngcontent-c0] {
    color: red;
}

If you omit the :host selector in the rule, however, your generated CSS will be this:

h2[_ngcontent-c0] {
    color: red;
}

Is there a behavioral difference between these two CSS rules? I understand using :host itself to style the top-level component element, but as soon as you nest to child elements, isn't :host pointless?

Upvotes: 2

Views: 133

Answers (1)

Daniel W Strimpel
Daniel W Strimpel

Reputation: 8470

:host is only needed when styling your component itself. You don't need to use it when creating selectors for the content within it.

If you add it to that rule (:host h2), you just increase the specificity of the rule (in case you need to do that). [_nghost-c0] h2[_ngcontent-c0] is more specific than h2[_ngcontent-c0] when calculating the order in which the CSS is applied.

Upvotes: 5

Related Questions