Is that possible to use css variable in css "background url"

5.5k views Asked by At

I would like to set a base domain with all of my pictures in CSS file, here's what I tried:

global.css

:root
{
  --bgd: #C0C0C0;
  --picdomain: "https://somedomain.com/";
}

s1.css

@import url("global.css");

body
{
  background-color: var(--bgd); //works if only it exist
  background: url(var(--picdomain)"some/path/images/pic.png"); //no effect
}

And load s1.css in html

<link rel="stylesheet" type="text/css" href="s1.css">

The HTML's background-color did changed, but background didn't show up. So I tried other way:

global.css

@picdomain: "https://somedomain.com";

s1.css

background: url("@picdomain/some/path/images/pic.png");  //can't read variable from imported css

didn't help

Only works while I set full URL for an image, like below:

global.css

:root
{
  --bgd: #C0C0C0;
  --picdomain: url("https://somedomain.com/some/path/images/pic.png");
}

s1.css

@import url("global.css");

body
{
  background-color: var(--bgd); //works if only it exist
  background: var(--picdomain); //no effect
}

But this isn't what I want......Is that possible to use css variable in "background"?

1

There are 1 answers

1
Zahid Gani On
    <style type="text/css">
    :root {
        --slide-1: url("{{url('public/assets/images/logo-nfs.png')}}"); /*this is laravel*/ 
        --slide-2: url("<?php echo 'images/logo-nfs.png';?>");  
    }`enter code here`

    .header111 {
      background-image : var(--slide-1); /*this is php*/ 
    }

    .header22 {
      background-image : var(--slide-2);
    }

    </style>

<div class="header111">
  test here 
</div>

<div class="header22">
  test here
</div>
<br>