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.
- CSS-loader
npm install --save-dev css-loader
- 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.
-
-
- .error{
- color: red;
- }
- [dir=ltr] .CanvasZone {
- padding-right: 8px;
- width: 1170px;
- margin: 0 auto;
- }
- #snackbar {
- color: #fff;
- text-align: center;
- border-radius: 2px;
- padding: 16px;
- position: fixed;
- z-index: 1;
- left: 50%;
- bottom: 30px;
- }
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.
- <div className="error">
- Please enter the username and password
- </div>
- <div id="snackbar">
- {this.state.toastMsg}
- </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.