Search code examples
csscss-variables

css variables - declare variable if not already defined


I have a project which is split up into the parent app, and several reusable child components in separate repositories. I'd like to define default CSS variables in these child components, which can be overridden by the parent app, however I can't find the right syntax for this. Here's what I've tried:

/* parent */
:root {
  --color: blue;
}

/* child */
:root {
  --color: var(--color, green);
}

.test {
  width: 200px;
  height: 200px;
  background: var(--color, red);
}

https://codepen.io/daviestar/pen/brModx

The color should be blue, but when the child :root is defined, the color is actually red, at least in Chrome.

Is there a correct approach for this? In SASS you can add a !default flag to your child variables which basically means 'declare if it's not already declared'.


Solution

  • CSS stands for cascading style sheets, so you cannot override anything by a parent...

    The only way is to create a stronger rule.

    look at .c1 and .p1

    .parent {
      --background: red;
    }
    
    .child {
      --size: 30px;
      --background: green; /* this wins */
    
      background-color: var(--background);
      width: var(--size);
      height: var(--size);
    }
    
    .p1 .c1 {
      --background: red; /* this wins */
    }
    
    .c1 {
      --size: 30px;
      --background: green;
    
      background-color: var(--background);
      width: var(--size);
      height: var(--size);
    }
    <div class="parent">
      <div class="child"></div>  
    </div>
    
    <hr />
    
    <div class="p1">
      <div class="c1"></div>  
    </div>