Search code examples
csssasscss-variables

How to handle/use path images with css variables? Angular


I receive a configuration JSON that has colors and the paths of the images that I must use in my CSS, I correctly set the variables in the html and it would have a result similar to this:

    <html lang="en" style="
--c-logo-square:https://linkener-design-tokens.s3.eu-west-1.amazonaws.com/localhost/temp%20belike%20small.png;
    --c-background-image:https://linkener-design-tokens.s3.eu-west-1.amazonaws.com/localhost/mainBg.png; 
    --c-primary:green; 
    --c-secondary:purple;">

I can use the color variables correctly, but I don't know how to use the image paths as background.

// Works
.my-html-component {
    color: var(--c-primary);
}

// Error
logo {
  background: url(var(--c-background-image));
}

When working with Angular and SCSS I understand that I could use some function that allows me to do what I need, but I don't know how to do it.


Solution

  • Instead of defining url in the attribute, define it as a part of the variable. Dont forget to add :root.

    :root {
    --c-background-image:url(https://linkener-design-tokens.s3.eu-west-1.amazonaws.com/localhost/mainBg.png); 
    }
    
    
    .logo {
      background: var(--c-background-image);
      width:500px;
      height:500px;
    }
    
    <div class="logo"></div>