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


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.


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 styles. In your case, you can add the CSS styles that you wanted to refer in your component.

How To Add Custom CSS File In SharePoint Framework (SPFX) Projects And Refer In Your Component
  1. /* css  file content */    
  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. }  

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

  1. 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> 

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


Popular posts from this blog

Get All content types from ContentTypeHub using SharePoint Rest API v2 using JavaScript

Save Location details to SharePoint Location column through SPFx and PnP JS

How To Create/ Generate QRcode In SPFx Web Part