Reputation: 143
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
component
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
Upvotes: 2
Views: 1381
Reputation: 364747
You have two choices, depending on whether you want to "look up", or "look down" the component tree:
Up - Use the :host-context()
pseudo-class selector to apply styles based on some condition outside a component's view (look up the component tree). You specify a component, element or class and Angular will look for it in any ancestor of the component's host element, all the way up to the document root. If it finds a match, the CSS style is applied to the component's view. @Günter already provided an example of this in his answer::host-context(twitter) .heart { ... }
Down - Use the /deep/
or >>>
selector to apply a style down through the component tree to all child component views. E.g., add this to the parent/twitter
component:
:host /deep/ .heart { ... }
Upvotes: 3
Reputation: 658235
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
.
Upvotes: 6