Is it possible to to get SASS to use its element's style's background-colour as a variable to use within it's functions?

Currently I'm generating these values within our API and passing them down but it would be simpler if this was something I could just do with SASS.

@function set-text-color($color) {
  @if (lightness( $color) > 40) {
    @return black;
  }
  @else {
    @return white;
  }
}

.example {
  .heading {
    font-size: 1.5em;
    padding: 1em;
    // color:set-text-color('element background colour');
  }
  .description {
    padding: 1em;
    // background: lighten('element background colour', 30%);
    // color:set-text-color('element background colour');
  }
}
<div class="example">
  <div class="heading" style="background-color: red;">
    Heading
  </div>
  <div class="description" style="background-color: red;">
    Nullam id sollicitudin mauris. Morbi vestibulum ullamcorper leo vel tristique.
  </div>
</div>
<div class="example">
  <div class="heading" style="background-color: yellow;">
    Heading
  </div>
  <div class="description" style="background-color: yellow;">
    Nullam id sollicitudin mauris. Morbi vestibulum ullamcorper leo vel tristique.
  </div>
</div>
<div class="example">
  <div class="heading" style="background-color: green;">
    Heading
  </div>
  <div class="description" style="background-color: green;">
    Nullam id sollicitudin mauris. Morbi vestibulum ullamcorper leo vel tristique.
  </div>
</div>
<div class="example">
  <div class="heading" style="background-color: blue;">
    Heading
  </div>
  <div class="description" style="background-color: blue;">
    Nullam id sollicitudin mauris. Morbi vestibulum ullamcorper leo vel tristique.
  </div>
</div>

1 Answers

0
Community On

No, you cannot do this directly in SASS: you cannot retrieve arbitrary CSS property values.

You can however create a SASS variable for your background color and then use that in your function like so:

@function set-text-color($color) {
  @if (lightness( $color) > 40) {
    @return black;
  }
  @else {
    @return white;
  }
}

$bg-color-1 = #fff;
$bg-color-2 = #000;

.example {
  .heading {
    font-size: 1.5em;
    padding: 1em;
    color:set-text-color($bg-color-1);
  }
  .description {
    padding: 1em;
    background: lighten($bg-color-2, 30%);
    color:set-text-color($bg-color-2);
  }
}

You could even combine these two with a mixin like so:

@mixin set-bg-color($bg-color:$bg-color-1){
     background-color: $bg-color;
     color: set-text-color($bg-color);
}

.example {
  .heading {
    font-size: 1.5em;
    padding: 1em;
    @include set-bg-color;
  }
  .description {
    padding: 1em;
    @include set-bg-color($bg-color-2);
  }
}