Search code examples
csscss-variables

Box-shadow with rgba variable


So I want to have a box-shadow with a Color variable in it. I saw on a post here that rgba(var(--card-border-color),0.75); works fine but having this inside a box-shadow Attribute breaks it. So this dosnt work:

box-shadow: 0px 0.46rem 2.18rem rgba(var(--card-shadow-color), 0.03),
    0px 0.93rem 1.4rem rgba(var(--card-shadow-color), 0.03),
    0px 0.25rem 0.53rem rgba(var(--card-shadow-color), 0.05),
    0px 0.12rem 0.18rem rgba(var(--card-shadow-color), 0.03);

How can I work around that?


Solution

  • Your code should be working fine, given that the following condition is satisfied: after the injection of the variable your color property is a valid CSS value. When you are using a hex code, this interpolates to rgba(#040914, 0.33) for example. This is not valid CSS—as per my comment, it is valid SCSS though, because the parser will convert it into a valid CSS RGBA color string.

    What you need is to deconstruct/convert your hex color into its RGBA counterpart for it to work, so that it will interpolate to something like rgba(4, 9, 20, 0.33). This is done by doing:

    --card-shadow-color: 4, 9, 20;
    

    See proof-of-concept below:

    .box {
      --card-shadow-color: 4, 9, 20; /* RGB equivalent of #040914 */
      
      box-shadow: 0px 0.46rem 2.18rem rgba(var(--card-shadow-color), 0.03),
        0px 0.93rem 1.4rem rgba(var(--card-shadow-color), 0.03),
        0px 0.25rem 0.53rem rgba(var(--card-shadow-color), 0.05),
        0px 0.12rem 0.18rem rgba(var(--card-shadow-color), 0.03);
        
      /* Presentational styles */
      width: 100px;
      height: 100px;
      margin: 50px auto;
      border: 1px solid rgba(var(--card-shadow-color), 0.1);
    }
    <div class="box"></div>