How To Add Custom CSS File In SharePoint Framework Projects And Reference It In Your Component

In this article, you will learn how to add a custom CSS file in the SharePoint framework (SPFx) projects and refer to it in your component.

Introduction

If you are working on classic SharePoint site, you know it is easy to refer to a CSS file or use inline CSS in the same file. In SPFx projects, you will have SCSS files created by default, which are similar to CSS files but with added capabilities, such as variables, nested rules, and mixins. There are cases you will have to refer to the custom CSS file. This article will help you how to add a custom CSS in your SPFx projects.

Installation

So, first, let’s start by installing the two loaders that help in loading the custom CSS files.

Run the below commands in the terminal/ in the node command prompt.

  1. CSS-loader
    npm install --save-dev css-loader
  1. Style-loader
    npm install style-loader --save-dev

It's recommended to combine style-loader with the css-loader.

Or, you could install them in one go,

npm install css-loader style-loader --save-dev

Adding a .css file

 
Under the src folder (as shown in the image), create a sub-folder - Styles. In src/Styles, create a file customCSS.css with the below content.

How To Add Custom CSS File In SharePoint Framework (SPFX) Projects And Refer In Your Component
  1. /* css  file content */    
  2.     
  3. .error{    
  4.     colorred;    
  5.     }    
  6. [dir=ltr] .CanvasZone {    
  7.      padding-right8px;     
  8.      width1170px;     
  9.      margin0 auto;    
  10.     }        
  11. #snackbar {    
  12.   color#fff/* White text color */    
  13.   text-aligncenter/* Centered text */    
  14.   border-radius: 2px/* Rounded borders */    
  15.   padding16px/* Padding */    
  16.   positionfixed/* Sit on top of the screen */    
  17.   z-index1/* Add a z-index if needed */    
  18.   left: 50%;     
  19.   bottom: 30px;     
  20. }  
Usage

Let’s import the CSS in our main component file (.tsx) as below.

require('./Styles/customCSS.css');

You can use the CSS as how you would in normal scenario.

  1. <div className="error">  
  2.         Please enter the username and password  
  3. </div>  
  4. <div id="snackbar">  
  5.    {this.state.toastMsg}  
  6. </div> 

Note
In React JS, we use className instead of class. class is a keyword in JavaScript and JSX is an extension of JavaScript. That's the principal reason why React uses className instead of class.