Chrillewoodz Chrillewoodz - 1 month ago 12
CSS Question

How to style child components from parent component's css file?

I've got a parent component:

<parent></parent>


And I want to populate this group with child components:

<parent>
<child></child>
<child></child>
<child></child>
</parent>


Parent template:

<div class="parent">
<!-- Children goes here -->
<ng-content></ng-content>
</div>


Child template:

<div class="child">Test</div>


Since
parent
and
child
are two seperate components, their styles are locked to their own scope.

In my parent component I tried doing:

.parent .child {
// Styles for child
}


But the
.child
styles are not getting applied to the
child
components.

I tried using
styleUrls
to include the
parent
's stylesheet into
child
component to solve the scope issue:

// child.component.ts
styleUrls: [
'./parent.component.css',
'./child.component.css',
]


But that didn't help, also tried the other way by fetching the
child
stylesheet into
parent
but that didn't help either.

So how do you style child components that are included into a parent component?

Answer

You can use encapsulation mode and/or piercing CSS combinators >>>, /deep/ and ::shadow

working example : http://plnkr.co/edit/1RBDGQ?p=preview

styles: [
    `
     :host { color: red; }
     :host >>> parent {
       color:blue;
     }
     :host >>> child{
       color:orange;
     }
     :host >>> child.class1 {
       color:yellow;
     }
     :host >>> child.class2{
       color:pink;
     }
    `
    ],

template: `
  Angular2                                //red
  <parent>                                //blue
      <child></child>                     //orange
      <child class="class1"></child>      //yellow
      <child class="class2"></child>      //pink
  </parent>      
`