2

I have a spfx web part the gets and displays list items. I'm not sure how to apply a theme to this web part so that the font type and style of the web part title and list items match the rest of the site. Are there recommended best practice ways of doing this?

4

The most common and straightforward way doing it is through SASS variables, available in office-ui-fabric module.

Prerequisites: you have SPFx template generated with React as javascript framework (knockout also works).

Now open any of your .scss files or modules (.module.scss) and add import at the top of the file:

@import '~@microsoft/sp-office-ui-fabric-core/dist/sass/SPFabricCore.scss';

By doing this you effectively include a set of variables available in ui-fabric-core module into your scss file. Now you can start using themed varibles to make your styles aligned with theme on a SharePoint website:

.my-selector {
  background-color: $ms-color-themeDark; // use dark color from SharePoint site theme
  border-color: $ms-color-themePrimary; // use primary color from SharePoint site theme
  color: $ms-color-white; // use white color from SharePoint site theme
}

During the build it will be translated to something like background-color: "[theme: themeDark, default: #005a9e]"; SharePoint understands this syntaxis and replaces it with actual values from the current theme. Which means that if you change a theme on your site, your webpart's colors will also be updated to match the theme.
To see the full list of all color varibles available, simply open node_modules\@microsoft\sp-office-ui-fabric-core\dist\sass\ThemeOverrides.scss

You can even go one step further and use spfx-uifabric-themes. With this module you can import the same list of variables, additionally, it contains some useful functions.
For example, if you want to apply error styles to your text, you can simply do below in your scss file:

@import './node_modules/spfx-uifabric-themes/office.theme';
.error {
  padding: 0 1em;
  line-height: 2em;
  @include stateStyle('error');
} 

which get translated to:

.error {
  padding: 0 1em;
  line-height: 2em;
  background-color: "[theme:errorBackground, default: #fde7e9]";
  color: "[theme:errorText, default: #333333]"
} 

This module also contains some useful functions for typography (based on SharePoint).
More reading - Use theme colors in your SharePoint Framework customizations

  • Thank you this is very helpful. Are font styles in the web part inherited from the sites theme? – chris rowles Nov 4 '18 at 8:17
  • 1
    They should inherit if you don't override them with custom values. – Sergei Sergeev Nov 4 '18 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.