Refer static resource in css of lightning component

you can certainly refer the static resource contents in your app/component.css using /resource/resource_name format.

Here's a sample app which I tried in my org to set div's background-image property by referring the slds loading image in the static resource.

testVFPage.app

<aura:application access="GLOBAL">
  <div>
     <div class="loading" style="height: 166px;width: 189px;">
     </div>
  </div>
</aura:application>

testVFPage.css

.THIS .loading{
    background-image: url(/resource/loading) 
}

Output:

enter image description here


I have tried the answer by Praveen and when viewing the CSS in a browsers developer mode the css url() appears exactly as typed, ie. it's not converting the path '/resource/loading' to the static resource URL. Strangely this answer here on Stack Exchange seems to be the only discussion about this.

The way I have achieved this today is by reverse engineering the static resources that the community template itself uses as provided by Salesforce (note this will obviously only work in the context of sites and communities).

The static resource is called PFResources and contains a folder structure like:

  • img
  • icons
  • css

Inside 'img' are the images I want to use for the footer background. So the class definition in the Lightning component CSS is:

.THIS .class {
      background-image : url('/sfsites/c/resource/PFResources/img/partnerships.jpg');
}

This is currently working in both the community builder, preview and while logged into the site as a user.

Update: This is a documented solution for using custom fonts in a community so will work as a long term solution. The following article describes accessing static resources in this way although doesn't explicitly make reference to image files; suggesting this isn't just a 'hack' but is intended behavior. Use Custom Fonts in your community


for the selected answer, the url needs to be in quotes:

.THIS .loading{
    background-image: url('/resource/loading') 
}

thanks Hutchenstein for the tip for the correct path for rendering within a community. this is just what I was missing for one my components.