user1806692 user1806692 - 1 year ago 198
CSS Question

Angular 2 Component scoped styles

Component scoped styles - how to style things differently depending on where they are in the site but still keep the styles scoped? Lets say I use the "heart like" item that we built in this course and I want to have lots of padding on the left but only if I nest this component within the twitter list that we built...but I don't want to have this padding if I have this heart component elsewhere - whats the best way to do this?? And can the styles for each scenario be scoped to just this component??

style below are in the heart.styles.css
so these are scoped to heart component.

This acts like global style for this component and
will apply no matter if it is nested in another component

how do you override this style if you don't want the padding
when it would be nested in another component lets say??

I have tried using the parent component css to override
but of course it wont work due to the scoping...and I don't
want to have some styles scoped and in one file and other styles
that aren't scoped because they have to sit outside the

You will end up with css all over the place with no idea
and potential scope/specificity issues??
.heart {margin: 0.1em 0 0 1.7em;}

I am probably being dumb about this but it is not obvious to me

Answer Source

The :host-context selector does this

:host-context(twitter) .heart {
  margin: 0.1em 0 0 1.7em;

When the element is a descendant of the <twitter> element, this style is applied to elements with class heart.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download