1

During the creation of styles, I had an idea of creating a CSS variable that represents the boolean value to display or not the transparency but I saw that the condition, unfortunately, does not work!

main.css

:root {
    --navbar-transparent: "true";
  }

navbar.component.scss

@if var(--navbar-transparent) == "true" {
.nav-booking {
    position: absolute;
    width: 100%;
    background: transparent;
    padding-top: 20px;
  }
} @else {
.nav-booking{
    border-bottom: 2px solid #d6d1d180;
 }
}

Is there a way to do this with CSS variables? Or is it impossible?

TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

2

You can hack an if() {} like below but I doubt you can do an if() {} else {}

* {
  --navbar-transparent: true;
  
}

.nav-booking {
    /* if !true */
    padding:var(--navbar-transparent,20px);
    border:var(--navbar-transparent,5px solid green);
    /*  */
    
    background:red;
    height:10px;
    margin:10px;
 }
<div class="nav-booking" ></div>

<!-- you need to set "initial" to get your false -->
<div class="nav-booking" style="--navbar-transparent:initial"></div>

Related to get mode detail around the use of initial

How to store inherit value inside a CSS variable (aka custom property)?

CSS custom properties (variables) for box model

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
1

In sass custom-properties are unfortunately just treated as a string, it doesn't associat a value.

However there are workarounds:

@function get($var) {
  @return map-get($custom-properties, $var);
}

$custom-properties: ();

@each $key, $value in $custom-properties {
  :root {
    --#{$key}: #{$value};
  }
}

Add any variable, you want to use within your Sass project and also be compiled to a custom-property, to this map: $custom-properties: ();.

$custom-properties: (
  'navbar-transparent': true,
  //...
);

Now use get($var) to acces said variables within your Sass project.

@function get($var) {
  @return map-get($custom-properties, $var);
}

$custom-properties: (
  'navbar-transparent': true,
);

@each $key, $value in $custom-properties {
  :root {
    --#{$key}: #{$value};
  }
}

@if (get(navbar-transparent)) {
  .nav-booking {
    position: absolute;
    width: 100%;
    background: transparent;
    padding-top: 20px;
  }
} @else {
  .nav-booking{
    border-bottom: 2px solid #d6d1d180;
  }
}

This will compile to:

:root {
  --navbar-transparent: true;
}

.nav-booking {
  position: absolute;
  width: 100%;
  background: transparent;
  padding-top: 20px;
}

https://codepen.io/LudwigGeorgImmanuel/pen/dypaXyE

Simplicius
  • 2,009
  • 1
  • 5
  • 19
  • I appreciate your very detailed answer, but we need to control the boolean from css file *main.css* exactly in :root {}, with your solution we will be obliged to control it from scss variable. – Salah Eddine Bentayeb Jan 17 '21 at 23:04
  • @SalahEddineBentayeb. Then you're stuck with Javascript, no way to achieve this with pure Sass. – Simplicius Jan 17 '21 at 23:10