Styling And Defining CSS In Angular App

Defining CSS in Angular app is very similar to defining HTML Templates.

Four Different Ways of Defining CSS In Angular

Within the component decorator, we can choose to write inline CSS, or we can use the Styles URL property to import an external style sheet, or you can write inline css within the Template property or additionally, we can also define CSS within a global style sheet. So, there are four different ways to defines CSS.

Playing With Some CSS Styling

When we start a new angular project, the Angular CLI generates an “app.component.css” file by default and defines it within the “styleUrls” property of the “app.component.ts” file.

Defining Css In Angular styleUrls

Defining Css In Angular styleUrls

Initially this file is blank when it is first created. Let’s add a simple rule that will set the color of h1 tag to a red color.

h1{color:red;}

Now, when we serve our angular app through the CLI, we can see the app reflects the changes immediately.

Adding Css Style To External Url

Adding Css Style To External Url

Now, lets use the same CSS through the “styles” property. Replace “styleUrls” with “styles” as below:

@Component({

selector:'app-root',

templateUrl:'./app.component.html',

styles: [`

h1{color:green;}

`]

})

The color should now change to green from red.

Next, let’s look at the global CSS rules set which can be defined through “styles.css” file.

If we just add the same style to the global file, you will notice that the change does not take place immediately. Since the preference is taken by Inline CSS Style as well as External Style Sheet over Global Style Sheet, the styles defined here gets minimized. Therefore, if there are any CSS styles defined in the template or external style sheet, that has to be removed first.

Finally, we can also write styles directly within the HTML template as we would write in regular HTML file.

<p style="color: green;"> Or does it? </p>

In these four different ways, we defining CSS in Angular app can be achieved.

  • Leave a Reply