`>*` selector not working from parent to child com

2020-04-18 08:07发布

问题:

I have the following Angular component

<div id="content-div">
  <router-outlet></router-outlet>
</div>

I place different components within the div above. My requirement is that all such components should have the css rule height:100%. Instead of duplicating this code, I tried to use >* css but that isn't working.

#content-div >* { 
  height:100%;
}

Does >* doesn't work across components? How could I make a child component take css rule from its parent?

回答1:

By default Angular encapsulates CSS. If you want to disabled this you need to do so in your component setup

@Component({
  selector: 'app-child-component',
  template: `<div class="parent-class">Child Component</div>`,
  encapsulation: ViewEncapsulation.None  // Use to disable CSS Encapsulation for this component
})


回答2:

You need to do it in the next way:

:host /deep/ > * {
   height: 100%;
}

But it's very unlikely you should do * it's very heavy and slow selector, it's better to limit yourself to something more specific, like the class on container or at least some tag.



回答3:

Had to change the approach. Instead of using >*, used css-grid. It worked.

#content-div{
  height:100%;
  display:flex;
  align-items: center;
  justify-content: center;
}


标签: css angular