GET IN TOUCH
+91-62843-00850
+1-732-668-8002
info@penthara.com
LOCATIONS
India
SCO 670, Third Floor
Sector 70, Mohali
Punjab, 160055
USA
651 North Broad Street
Suite 206
Middletown, DE 19709
Follow Us on Social -
02.08.2021

How to implement CSS in SPFx in Different Ways

There are a couple of ways to add CSS into HTML within SPFx solution and in this article, you are going to learn how to do in different ways and advantages and disadvantages of using those ways. You will learn what CSS is and most importantly how to add dynamic classes in SPFx solution.
CATEGORIES:
SHARE THIS BLOG:

Introduction

Modern SharePoint is aimed to make the user experience more collaborative, but the users also know that visual customization is not that vast. Where Microsoft makes the Modern SharePoint easy to manage and configure, an organization’s basic need is to render its theme of colors, font or style which still has its own challenges.

The development of SPFx technology allows developers to experiment with the customization of web parts. This not only limits the extent to functionality but also allows them to configure their web pages.

A very common way of styling your page is through CSS (Cascading Style Sheets). CSS handles the look and feel part of a web page.

WHY CSS ?

CSS helps you to keep the informational content of a document separate from the details of how to display it. The details of how to display the document are known as its style. You keep the style separate from the content so that you can:

  • Avoid duplication of common styling.
  • Make maintenance easier.
  • Use the same content with different styles for different purposes.

You use HTML to describe the content of the document, not its style; you use CSS to specify its style, not its content. There are exceptions to this rule, of course, and HTML also provides some ways to specify style. For example, in HTML you can use a <b> tag to make text bold, and you can specify the background color of a page in its <body> tag. When you use CSS, you normally avoid using these HTML style features so that all your document’s style information is in one place.

Ways to implement CSS in SPFx

Today we are going to see just two ways of implementing CSS in your SPFx solutions. Ideally, this should suffice for majority of your needs. This is also in no way a complete and comprehensive way of implementing CSS in your SPFx solutions. There are other methods as well that have not been discussed.

Using Inline CSS in SPFx webpart

Inline CSS is considered useful as it reduces the number of files that the browser needs to download before displaying the web page. With an external CSS, the browser first loads an HTML file and then downloads the CSS file. With an inline CSS, you just need to download one HTML file instead of 2, making the process a little bit faster.

An inline CSS is used to apply a unique style to a single HTML element by using the style attribute of an HTML element. The following example sets the border color of the <div> to black while using React framework within your SPFx solution:

Below is the formula written in the formula bar:

<div className={`ms-Grid-col ms-u-md3`} style={{"border-color":"black"}}>
<p>Hello World</p>
</div>

Similarly, if you want multiple attributes, try comma separated values as below:

<div className={`ms-Grid-col ms-u-md3`} style={{"border-color":"black","font-size":"12px"}}>
<p>Hello World</p>
</div>

Using dynamic classes via JavaScript

Another way of adding CSS is by using dynamic classes.

The definition ${styles.helloSPFx} in the TypeScript/JavaScript code is a called template literal. This reference to the object property styles.helloSPFx gets automatically replaced with the compiled style class name. After this change, the web part renders properly.

By generating this unique class name out of the defined generic class name, SPFx makes sure that the CSS added to the page only affects the web part and not the rest of the page.

Below is the react code for our helloWorld.tsx file

public render(): React.ReactElement< helloWorldProps> {
return (

Adding CSS in SPFX solution

);
}

And our index.scss file will look like –

@import "~office-ui-fabric-react/dist/sass/References.scss";
.helloo {
background-color: $ms-color-themeDark;
p {
color: red;
text-align: center;
}
}

The compile style sheet corresponding to the web part looks like this with dynamic class.

<div class="helloWorld_bd9858bb">
<p>Adding CSS in SPFX Solution</p>
</div>

And the output will be –

Dynamic class output

Among the many advantages of inline CSS, putting CSS into the head section of HTML ensures that your web browser doesn’t have to download a separate external file. It saves a round trip to the browser. It’s a good practice to inline the CSS of landing or home pages so they can load faster and be effectively viewed.

Advantages of Inline CSS:

  • Inserting CSS rules in HTML pages becomes easy and quick that’s why this method is useful for testing and previewing changes and for performing quick fixes to your website.
  • You do not need to create and upload a separate document as in the external style.

Disadvantages of Inline CSS:

  • Adding CSS rules to every HTML element is a lot time-consuming and makes your HTML structure untidy. It also makes debugging code while texting a bit complex.
  • Styling multiple elements can affect your page’s size and download time.
  • There is a lot of code repetition as if we want to change a button’s color to RED, we will have to change it everywhere. Thus, it increases our effort, decreases our productivity and is also time consuming.

Using External CSS

The UI of your solutions often consists of multiple building blocks. These building blocks are called components. Splitting your solution into multiple components allows you to simplify the development process and makes it easier to test and reuse the components in your solution.  Because components have a presentation, they often require CSS styles. Ideally, components should be isolated and be able to be used on their own. With that in mind, it makes perfect sense for you to store CSS styles for the particular component along with all other asset files next to the component.

So by creating index.css and importing it to your file, we can achieve our goal. By keeping all your CSS for different components and files created in a common place and importing it into your component.

import "./index.scss";

And adding dynamic loading with SPComponentLoader

SPComponentLoader.loadCss(this.context.pageContext.site.absoluteUrl + 'FilePath.css');

One more thing a developer can do is to use Centralized CSS. By using this we can keep our CSS in the same file and work from there. It makes our CSS a little untidy though, but we can use it for small projects.

So, if we are using a common modal or pop up, we can write its CSS in a Centralized CSS file so that we do not have to write the same code again and again.

Advantages of External CSS:

  • Your HTML files will have a cleaner structure and will be smaller in size because now the CSS code is totally kept in a different file.
  • You can use the same .css file for multiple pages. It will increase our productivity and decrease repeated effort.

Disadvantages of External CSS:

  • Your page will only work once the CSS file is loaded. The page will not be rendered correctly until the external CSS is loaded.
  • Uploading or linking to multiple CSS files can increase your site’s download time.

Conclusion

Putting your CSS code in a separate file is highly recommended. The primary benefit of an external stylesheet is that it can be reused by multiple components. As a result, if all HTML on your site uses the same external stylesheet, changes to this stylesheet will be reflected in all of the HTML pages of your site.

The most common rule of CSS is to keep your CSS in an external file and only add inline CSS for fancy stuff like animations and all. But do keep in mind to keep it to the minimum. The inline formatting will overwrite all the other styles when used, so keep the CSS Specificity in mind. For more details, please refer to this link.

Written By
Nivedietta
Nivedietta Singh
Web Developer
peer reviewed By
Jasjit Chopra
JAsjit Chopra
chief executive officer
Graphics designed By
Sanika Sanaye
sanika sanaye
Creative Design Director
Recommended Content
Email Insights
Get the latest updates from Penthara right in your mail box.
Sign Up
LinkedIn Newsletter
Monthly updates, news & events from Microsoft to help  your business grow.
Subscribe To Newsletter

Leave a Reply

Your email address will not be published.

More From This Category

Exploring advanced customizations of react-table component within SPFx solution

Learn how to customize react-table within SPFx solution. In this blog post we have covered some advanced customizations and configuration options like conditional rendering of table data, adding hyperlink to table row, making a single cell clickable in a row, and maintaining pagination with react-table.

Read More
Quickly work with SharePoint API calls with Postman

Overview SharePoint APIs are used in various platforms to perform basic as well as complex actions. Two places where these APIs are used vigorously are: SPFx Solutions Power Automate Custom Applications The challenge faced while developing these solutions is that, there is no easy and quick way to test or execute these API calls in […]

Read More
Different use case scenarios of useEffect in SPFx React solutions

What is useEffect in React UseEffect is a hook in react which was created to be used in a functional component. useEffect hook can be used in different scenarios depending on our need i.e. it can provide lifecycle functionality of class component as componentWillMount or componentDidMount. For more detailed information you can refer to the […]

Read More