0

I am trying to use static resource image in CSS using the below code -

JS:

//Importing image from static resource
import My_Resource from '@salesforce/resourceUrl/popUpImage';

//Defining this inside export classs
popUpImage = My_Resource;

CSS:

.bgImage{
    background-image: url({!URLFOR(popUpImage)});
  }

Please help :(

3
  • Does this answer your question? how do we access the image files from static resource in css? Commented Aug 16, 2022 at 7:28
  • 1
    @McCubo I think URLFOR is not valid in LWC context Commented Aug 16, 2022 at 7:51
  • @RubenDG I was thinking of using the second answer in the post, to pack everything in a single zipped folder. so you can use relative paths. Commented Aug 16, 2022 at 7:56

3 Answers 3

0

In the CSS file you cannot access property of your JS file.
Anyway you could provide a getter for your CSS rule in your JS class in order to set an inline style to the appropriate tag

JS

get bgImageStyle() {
    return `background-image: url(${My_Resource})`;
}

HTML

<div style={bgImageStyle}>
    something
</div>
1
  • 1
    This works but all I needed is this which worked for me - background-image: url('/Resource/mypopup'); Commented Aug 17, 2022 at 16:57
2

This is a use case for a CSS variable:

:host {
    --background-image-url: 'default.jpg';
}
div {
    background-image: var(--background-image-url);
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    display: inline-block;
    height: 20em;
    width: 100%;
}

Then, in your JS:

renderedCallback() {
  this.template.host.style.setProperty('--background-image-url',`url(${My_Resource})`);
}

Demo.

0

try this not in the CSS, but in the HTML: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_resources

1
  • Welcome to Salesforce Stack Exchange (SFSE)! Link-only answers are discouraged and may be deleted. (See: Why and how are some answers deleted?) Please edit your answer to add more information. (From How do I write a good answer?: "...please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link....") Commented Aug 16, 2022 at 11:42

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.