3

I have my background.png file in my staticresource folder, when I set it as an image I could be able to see that image in application, but if I set as background image ,it is not visible.why is it so?

CSS:

   .background_img {
    background-image: url('../../staticresources/background/background.png');
     }

The above given code is what I added in css.

HTML:

<div class="background_img">
      <div style= {backgroundUrl}>
        <h1>Salesforce project</h1>
    </div> 
</div>

JS:

 import { LightningElement } from 'lwc';
 import  backgroundUrl from '@salesforce/resourceUrl/background';
 export default class Sampleapp extends LightningElement {
 get backgroundStyle() {
   return `height:50rem;background-image:url(${backgroundUrl})`;
  }
 }

2 Answers 2

4

You need to import the static resource url and then use it.

Here is example:

enter image description here

HTML:

<template>
  <div style={backgroundStyle}>
  </div>
</template>

JS:

import { LightningElement } from 'lwc';
import backgroundUrl from '@salesforce/resourceUrl/background';

export default class Poc extends LightningElement {
    get backgroundStyle() {
        return `height:50rem;background-image:url(${backgroundUrl})`;
    }
}
0
1

You could store the image in a static resource, and in the CSS file of the Lightning web component you could use the below mentioned syntax.

background-image: url('/resource/static_resource_name');
3
  • How is this answer different from the one already posted?
    – glls
    Commented Mar 24, 2021 at 18:11
  • @glls this is CSS, the first answer is returning a CSS string via JavaScript.
    – binaryLady
    Commented Apr 14, 2021 at 15:25
  • You can also use this one background: url('/resource/ImagesFolderName/someimagename.svg') this one worked for me by putting it in lwc css file
    – Shubham
    Commented Aug 1, 2023 at 14:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .