skip to Main Content

Issue details

All the styles are loading in component except body tag. I need to set body style from within the login component. Is that possible?

I have already checked the link but not working for me: Changing body css from within an Angular component

login.component.css Code

body {
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: #eee;
}

Component Code

import { Component } from '@angular/core';

@Component({
    selector: 'login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css'],
    host: {
        class: "loginbody"
    }
})
export class LoginComponent {

}

2

Answers


  1. Based on the documentation: https://angular.io/guide/component-styles#style-files-in-component-metadata, it is intended that your component style shouldn’t affect the global style. In fact, it is generally not recommended to have your styling "bleed" outside of your component’s scope.

    If you want to style the elements outside of your component, specify a global style file in angular.json instead following this guide: https://angular.io/guide/component-styles#external-and-global-style-files

    If you really want to do it, you can use the CSS below instead:

    ::ng-deep body {
        padding-top: 40px;
        padding-bottom: 40px;
        background-color: #eee;
    }
    
    Login or Signup to reply.
  2. You can use ViewEncapsulation.None in your component to apply the styles to other elements also.

    @Component({
        selector: 'login',
        templateUrl: './login.component.html',
        styleUrls: ['./login.component.css'],
        host: {
            class: "loginbody"
        },
        encapsulation: ViewEncapsulation.None // <----add this line
    })
    export class LoginComponent {
    
    }
    

    then if you write css style in the login.component.css to style the body. It should apply the styles.

    From the docs:

    ViewEncapsulation.None

    Doesn’t provide any sort of CSS style encapsulation, meaning that all the styles provided via styles or styleUrls are applicable to any HTML element of the application regardless of their host Component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search