I want to set the background image of a div from the variable "imageUrl". I get the imageUrl from a variable in the js. The img src part of the html code works. But getting the variable into the style has not. Am I just not escaping the code correctly? Or not calling out the variable correctly? Here is my code:

<div class="slds-p-top_xxx-small" style="background-image: url('\'+imageUrl+\'');">
    Your newer selected image is: <lightning-formatted-url value={imageUrl}></lightning-formatted-url>
    <img src={imageUrl}>Test</img>
    <h1>Your screenname is {screenName}</h1>
    <h1>Your navLogic is {navLogic}</h1>
    <h1>Your Component Text is {componentText}</h1>


1 Answer 1


You can't use "expressions" in LWC. You need to make a separate getter for this:

get imageUrlStyle() {
  return `background-image: url("${this.imageUrl}")`;


<div class="slds-p-top_xxx-small" style={imageUrlStyle}>
  • Thanks! I tried using something like this before but I got turned off by the errors I got in VS Code. I recently read where I could ignore them and it works perfectly. Thanks so much for your help. Mar 16, 2021 at 23:57
  • @JonathanCrow You'll eliminate a good potion of those errors if you add // jshint esverson: 9 to the top of your JS source files, and configure eslint to use es9 as well (I forget how off the top of my head, but a simple Google search should be illuminating).
    – sfdcfox
    Mar 17, 2021 at 1:47

You must log in to answer this question.

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