1

I've followed step-by-step this article on how to inject CSS in modern SharePoint pages using Extensions:

https://tahoeninjas.blog/2018/05/08/inject-custom-css-on-sharepoint-modern-pages-using-spfx-extensions/

Everything works perfectly in localhost but not when using CDN. The css is apparently just ignored.

This is the code that I am using in my OnInit method:

    const cssUrl: string = this.properties.cssurl;

    if (cssUrl) {
        // inject the style sheet
        const head: any = document.getElementsByTagName("head")[0] || document.documentElement;
        let customStyle: HTMLLinkElement = document.createElement("link");
        customStyle.href = cssUrl;
        customStyle.rel = "stylesheet";
        customStyle.type = "text/css";
        head.insertAdjacentElement("beforeEnd", customStyle);
    }

My goal is to inject this css to hide the left-side navigation and place the search on top of the page.

nav[role='navigation'] {
    display: none !important;
}
div[class^='searchBox_'] {
    position: absolute;
    right: 200px;
    top: 20px;
}
div[class^='pageContainer_'] {
    left: 0 !important;
}

Again, in localhost it works great. Well, not perfect because there is a delay fot the changes to occur, especially in the first access. But I can live with that.

when using --ship things don't work.

Is there an alternative way of accomplishing this?

1

You can use the below ready-made SPFx modern script editor web part.

Steps to deploy:

  1. Clone or Download the webpart from here

  2. Edit the Write-manifests.json.

  3. Build the package
  4. Build the package and deploy

For details steps refer to the below article :

Add The Script Editor Webpart back to SharePoint Modern Experience

| improve this answer | |
1

Alternative

This sample was just added to sp-dev-fx-webparts: https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-add-js-css-ref

It lets you add JS and CSS references on Modern Pages via SPFx application customizer extension.


For your own solution to work, make sure that all the steps under Deploying to your production tenant has been followed.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.