AI Hints
Home›Angular Tutorial›Using Components Together, Component Styles and Practice: A Book Card
Angular · Lesson 26 of 120

Component Styles

CSS that stays inside.

⏱ 2 min read▶ Video at 31:47🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

In a big app, CSS can easily clash. A rule for one part of the page breaks another part. Angular solves this by keeping each component's styles inside it.

  • CSS can clash
  • One rule breaks another
  • Styles stay inside

Scoped styles

Styles in a component only apply to that component's template. A rule for p, inside the card, won't touch paragraphs elsewhere. Colon host styles the component's own tag. And styles dot css, in the source folder, is for global styles, that apply everywhere.

keyvalue
Component stylesonly this template
p { ... }only this card's paragraphs
:hostthe component's own tag
src/styles.cssglobal styles

A styled card

Colon host gives the card a red border, and rounded corners. And a rule makes paragraphs crimson, and bold.

book-card.tstypescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-book-card',
  template: `
    <h3>Dune</h3>
    <p>Only 3 left in stock!</p>
  `,
  styles: `
    :host { display: block; border: 3px solid red; border-radius: 12px; padding: 0 16px; }
    p { color: crimson; font-weight: bold; }
  `,
})
export class BookCard {}

The rules stay inside

App shows the card, and then a paragraph of its own. Run it. The card's paragraph is crimson, and bold. But App's paragraph, under the card, is unchanged. The card's rule stayed inside the card.

app.tstypescript
import { Component } from '@angular/core';
import { BookCard } from './book-card';

@Component({
  selector: 'app-root',
  imports: [BookCard],
  template: `
    <app-book-card />
    <p>Free delivery on orders over £25.</p>
  `,
})
export class App {}
Also uses book-card.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-book-card',
  template: `
    <h3>Dune</h3>
    <p>Only 3 left in stock!</p>
  `,
  styles: `
    :host { display: block; border: 3px solid red; border-radius: 12px; padding: 0 16px; }
    p { color: crimson; font-weight: bold; }
  `,
})
export class BookCard {}

Summary

Component styles only apply inside the component, colon host styles its tag, and styles dot css is for global rules. Next, some practice.

Key takeaways
  • Scoped styles
  • :host
  • src/styles.css
Next up: Practice: A Book Card — your turn