SharePoint Online Branding Inject CSS

To be able to inject CSS in the SharePoint Online Portal you have to use the Application Customizer template when you create an SPFx webpart.
Then it is just a matter of create a style element and injecting it in the head of the page.
So launch your PowerShell window and type

yo @microsoft/sharepoint

Choose a name for your solution, then choose SharePoint Online only as target, choose a folder, don't allow tenant admin to be able to deploy the solution on all sites.
The client-side component in our case is an extension and the type of extension is Application Customizer. Give it a name and a description and wait for the project creation.
When it is finished type

code .

to open visual code.

This is how your shell should look like

 

Now the fun begins. Open your .ts file it should be something like YOUR_APPLICATION_NAMEApplicationCustomizer.ts and replace the content of the OnInit() method by

    Log.info(LOG_SOURCE, `Initialized ${strings.Title}`);

    const head: any = document.getElementsByTagName("head")[0] || document.documentElement;
    let customStyle: HTMLLinkElement = document.createElement("link");
    customStyle.href = this.context.pageContext.site.absoluteUrl+"/SiteAssets/cdn/customCSS.css";
    customStyle.rel = "stylesheet";
    customStyle.type = "text/css";
    head.insertAdjacentElement("beforeEnd", customStyle);

    return Promise.resolve();

In this script we are getting a reference on the head element of the page then creating a new link element, setting its href to some css we have in our SharePoint Portal and injecting this element as the last child of the head element.

Using this method you are sure that your CSS will be loaded at the right time.

All source code is available on git hub at https://github.com/alaabitar/branding

Add comment