[SOLVED] How can I reference an image from my assets folder in some CSS?

For example, I have a button class in my CSS:

.button{   
    background-image: url('some_local_image.png');
}

…but what is the correct method/path to reach the local image in my assets folders?

EDIT. I also tried without success…

background-image: url(assets/Images/my_image.png);

I even tried to replace the background image using Javascript like this:

this.help_close_button_image = this.app.assets.find('close_image.png').getFileUrl();
this.help_close_button.style.backgroundImage  = this.help_close_button_image;

This seemed to get the image without problem but nothing is actually displayed in the background of my button element.

Thanks

Hi @Grimmy,

We do that quite often in our projects, as you figured out you need to get the file url from your asset:

const url = this.app.assets.find('close_image.png').getFileUrl();

And using either way add it in your CSS. Either by scanning your CSS code before appending it to an element and replacing the url, or by using JS to set the backgroundImage property.

For example I use an ID to target the element:

const element = document.getElementById('my-id');
element.style.backgroundImage = `url(${url});`;

If that doesn’t work, try using the browser dev tools to debug:

  1. Is the image url correct? Log it in the console and try opening it.
  2. Has the url correctly being added to the element style?
1 Like

Thanks. It seemed I needed to use this syntax:

this.help_close_button.style.backgroundImage = url(‘${this.help_close_button_image}’);

1 Like