Saher Elgendy
Saher Elgendy

Reputation: 1619

How to style html and body from the main Angular component?

I am trying to style html and body from the main component:

app.component.styl:

 html, body {
       padding: 0;
       margin: 0;
       background: blue;
    }

and seems it does not work with my angular component:

app.component.ts:

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.styl']
    })
    export class AppComponent {

    }

app.component.html:

<div class="todo-app">
  <div>
    <input type="text">
    <button>Add</button>
  </div>
</div>

Why html and body selector don't work, is there a special angular method to achieve that??

Upvotes: 5

Views: 6312

Answers (3)

SeleM
SeleM

Reputation: 9658

If you'd enabled Stylus preprocessor on your project, you have two ways AFAIN to apply your Styles on your root file.

1-Through your general styles.styl file

2-Through the index.html file itself

Upvotes: 1

Carlos Osiel
Carlos Osiel

Reputation: 446

If you need that the style is apply to all project, you need to deactivate Encapsulation in css,

@Component({
   ...
   encapsulation: ViewEncapsulation.None
   ...
})

Here a nice article about that. But I recommend you set the style in style.css or style.scss in the root of your project.

Upvotes: 3

IvanS95
IvanS95

Reputation: 5742

The app.component is located inside the index.html's body tag; like this

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Alerts</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="assets/img/favicon/favicon.ico">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root></app-root> <!-- This is your App Component -->
</body>
</html>

Given that, you can't target body or html with the default behavior (that means if ViewEncapsulation is enabled), since styles are scoped to that component only, and the component itself DOES NOT have a body tag; you need to define the styles in the styles.css global file, or turn ViewEncapsulation off for that component so the styles defined in its css file apply globally

Upvotes: 7

Related Questions