Search code examples
htmlcssmaterial-designcdnmaterial-components-web

How to set primary and secondary colors in Material Design Components for Web?


Details

I went looking into Material Components (MDC) for Web and landed to using CDN (hosted CSS and JavaScript libraries):

  • https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css
  • https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js

This is by virtue from their getting-started-docs-page in [1]. Similarly, MDC has this predecessor-slash-lighter-library Material Design Lite (MDL) which you could easily customize the theme colors. It can be done through its custom CSS theme builder. [2]

However, according to MDC Web's Theming Guide: [3]

... At the moment, MDC Web supports theming with Sass and with CSS Custom Property, with plans for CDN support as well, once that service is available.

It turns out, modifying the theme colors through the MDC's CDN URL is currently not an option.

So again back to my question, how could one set the primary and secondary colors in the new MDC for Web using the CDN?

References

  1. Getting started, Material Components for the Web
  2. Custom CSS theme builder, Material Design Lite
  3. Theming guide, Material Components for the Web

Solution

  • If you're using MDC Web's CSS from CDN, you can modify a theme using CSS custom properties (variables) like this:

    /* my-style.css */
    
    :root {
      --mdc-theme-primary: #fcb8ab;
      --mdc-theme-secondary: #feeae6;
    }
    

    The full list of CSS custom properties for MDC Theme is here. For instance, here how you can modify text color on top of a primary/secondary backgrounds:

    /* my-style.css */
    
    :root {
      --mdc-theme-primary: #fcb8ab;
      --mdc-theme-secondary: #feeae6;
      --mdc-theme-on-primary: #fff;
      --mdc-theme-on-secondary: #fff;
    }
    

    Note that this CSS should come after importing the MDC Web's CSS file, e.g.:

    <link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
    <link rel="stylesheet" href="my-style.css">
    

    MDL theme customizer you've mentioned has nothing to do with MDC Web. MDL is an MDC Web's predecessor which is deprecated in favor of MDC Web.