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

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'); Aug 17, 2022 at 16:57
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....")
    – Moonpie
    Aug 16, 2022 at 11:42
0

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.

You must log in to answer this question.

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