Search code examples
angularangular-material

How to change the font family in material v18


I am following the documentation of

https://material.angular.io/guide/theming#defining-a-theme

// From documentation

$theme: mat.define-theme((
  
  typography: (
    brand-family: 'Open Sans',
    bold-weight: 900
  ),
));

html {
    @include mat.core-theme($theme);
    @include mat.all-component-themes($theme);
    @include mat.all-component-typographies($theme);
}

and tried the answer from

Font-Family Change on Angular Material

//  Answer based on stackoverflow

$my-theme: mat.define-theme($config: (
    typography: (
      plain-family: '"Open Sans", sans-serif',
      brand-family: '"Open Sans", sans-serif',
    ),
  ),);

  :root {
    @include mat.all-component-typographies($my-theme);
  }

none of the options worked. Let me know how to change the font family on material v18

PS: Do not comment there are already answers. Those are for previous versions which do not work for v18


Solution

  • The problem is that by default, the typography only applies to the Material components and not to the rest of the app. To fix it, include the typography hierarchy mixin in your styles.scss:

    @include mat.typography-hierarchy($theme);
    

    This exposes additional CSS classes such as mat-typography. In your index.html, you can use this class on the body element to apply your typography to the whole app:

    <body class="mat-typography">
      <!-- ... -->
    </body>
    

    You don't need to add this class to the body, you can add it to any element. This also allows more granular use of the typography.