2

I have the following css ID:

#SecondaryLayout__rightBgImg {
  background-image: "SOMETHING IS GOING TO BE HERE";
  height: 800px;
  width: 100%;
  background-size: cover;
}

and I have the following HTML Element:

<div id="SecondaryLayout__rightBgImg">...</div>

I need to be able to set the background image from the HTML element, so what I did is that I changed the HTML element to the following:

<div id="SecondaryLayout__rightBgImg" img="/somewhere/photo.jpg">...</div>

and changed the css ID to the following:

#SecondaryLayout__rightBgImg {
  background-image: url(attr(img)); /* LOOK HERE */
  height: 800px;
  width: 100%;
  background-size: cover;
}

However, this url(attr(img)) isn't working.

but why? and is it possible to nest function calls in css? what is the better approach for this case?

Normal
  • 1,616
  • 15
  • 39
  • Are use using this for a class or an id only? If this is for a single element could you not just specify the URL directly in the css rather than using the `attr()` function? – Daniel Black May 11 '22 at 18:52
  • attr used in anything other than content does not seem to be supported by any browser yet see https://caniuse.com/?search=attr Is there a reason for not setting it in a style attribute? – A Haworth May 11 '22 at 18:54
  • @DanielBlack, actually the problem is over complicated way than that. I am using React (JSX) with Redux, but this was the portion of the problem that happened while I was developing in React – Normal May 11 '22 at 18:55
  • For my code case, Since I am using React (JSX), I can specify the style property directly on the HTML element itself, and then I can add the background-image url there by specifying the changing variable there. If you say it's complicated and not recommended, then I'll just go and do that. but I was just thinking if it was possible to abstract the styling code from the logical programmatic part. – Normal May 11 '22 at 18:59

0 Answers0