0

I'm currently trying to make a css background that will change size depending on the size of the screen, so I tried to use a variable like that :

var root = document.documentElement;

document.addEventListener('resize', () => {
  root.style.setProperty('--screen-x', window.screenX)
  root.style.setProperty('--screen-y', window.screenY)
})
#element {
   background-image: url(https://picsum.photos/var(--screen-x)/var(--screen-y)?random=3);
}

Btw, there is 4 differents elements with the random from 1 to 4 to get 4 separate images with picsum.

Sorry if I'm not clear, english is not my first langage :(

It obviously doesn't work, but I wonder if there would be a way to do it ? (get the variables in the url)

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
  • Does this answer your question? [string concatenation in css](https://stackoverflow.com/questions/15745492/string-concatenation-in-css) – Niklas E. Jun 30 '23 at 08:53
  • Does this answer your question? [Is there a way to interpolate CSS variables with url()?](https://stackoverflow.com/questions/42330075/is-there-a-way-to-interpolate-css-variables-with-url) – evolutionxbox Jun 30 '23 at 08:55
  • No, none of these answers were concluent. Is there a way to make it with JavaScript maybe ? – Jonas Barth Jun 30 '23 at 09:02
  • https://stackoverflow.com/a/42331003/989920 is the answer you're looking for and the same as the one posted below – evolutionxbox Jun 30 '23 at 09:07
  • I don't think that's what I'm looking for, I want to **include** the var in the url – Jonas Barth Jun 30 '23 at 09:17

1 Answers1

0

A messy solution

var root = document.documentElement;

resize()

document.addEventListener('resize', () => resize)

function resize() {
root.style.setProperty('--url', `url(https://picsum.photos/${window.screenX}/${window.screenY}?random=3)`)
}
:root {
  --url: "";
}

#element {
   width: 100vw;
   height: 100vh;
   background-image: var(--url);
}
<div id="element"></div>
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • I wonder why the screen size is 41x45? – evolutionxbox Jun 30 '23 at 09:01
  • 1
    @evolutionxbox `screenX` isn't width, it's a distance from the left of browser window. Op probably wanted to use `innerWidth` and `innerHeight` – Konrad Jun 30 '23 at 09:04
  • It does not seem to work, the background has literally no value when I run my code so I don't know what to do. Do you want the full code to see ? – Jonas Barth Jun 30 '23 at 09:12
  • Here is the link of the CodePen of the website if you need [CodePen](https://codepen.io/daiki4529/pen/jOQmygK) – Jonas Barth Jun 30 '23 at 09:21