Change color depending on background color with Sa

2019-06-21 20:17发布

问题:

This question already has an answer here:

  • Sass - Manipulate inherited property? 4 answers

I want to set up some sass color rules that will automatically choose the font color variable for me. I want the text color to be dependent on what color the background color of the parent div is.

If

div {background-color: #000; }

Then

div p { color: #fff; }

How can this be achieved with sass?

回答1:

You could use lightness() function for the background-color to determine the color value, as follows:

@function set-color($color) {
    @if (lightness($color) > 40) {
      @return #000;
    }
    @else {
      @return #FFF;
    }
}

Then use the above function as below:

div { background-color: black; // Or whatever else }
div p { color: set-color(black); }

LIVE DEMO.



回答2:

You could use control directives.

It depends on the purpose, but there might be easier ways to change a background color depending on a certain condition, such as Javascript.