Search code examples
angularangular7angular8

How to override CSS styles of component in Angular?


I have a custom component <app-button><span></span></app-button>.

It has CSS styles like:

span:hover {
   color: red;
}

When I use this component in another and tried to apply CSS styles in parent component it has not effect:

<app>
<app-button></app-button>
</app>

Inside app component I have tried:

  app-button span:hover {
       color: green;
    }

It does not work for me


Solution

  • you could use the ng-deep selector:

    ::ng-deep app-button span:hover {
        color: green;
    }
    

    which will make your styles penetrate to child components. but this functionality is due to be deprecated soon according to the angular team, and people are advised to get off of it. (PERSONAL opinion: too many projects rely on ng-deep for them to deprecate it anytime soon)

    the best way to do it currently IMO is with a global style sheet with something like:

    app app-button span:hover {
        color: green;
    }
    

    you also could set the view encapsulation to none on your parent component, but that's functionally similar to a global style sheet, and can be confusing if you don't set things up correctly and forget where / why you put global styles that only load when a component loads, and leads to some bugs in my experience.