Conditional CSS based on background color variable

2019-07-20 20:59发布

问题:

I realise this is a similar question to this Conditional CSS based on background color variable

but I need to do it inside a loop in LESS. If a background colour is too dark I want to generate another class so I can make the text on top lighter but not sure how as I don't think you can use lighten and darken functions with hex colours...?

Here is my LESS http://codepen.io/anon/pen/IlsJE?editors=110

.for(@i, @n) {.-each(@i)}
.for(@n)     when (isnumber(@n)) {.for(1, @n)}
.for(@i, @n) when not (@i = @n)  {
.for((@i + (@n - @i) / abs(@n - @i)), @n);}

// .for-each

.for(@array)   when (default()) {.for-impl_(length(@array))}
.for-impl_(@i) when (@i > 1)    {.for-impl_((@i - 1))}
.for-impl_(@i)                  {.-each(extract(@array, @i))}

// PAs
@pa1: "pa1";
@pa2: "pa2";
@pa3: "pa3";
@pa4: "pa4";

// Colors
@pa1-color: #72afb6;
@pa2-color: #9fad9f;
@pa3-color: #8dd8f8;
@pa4-color: #00567A;

// Setting variables and escaping them
@pas: ~"pa1" ~"pa2" ~"pa3" ~"pa4";

// Define our variable   
.define(@var) {
  @pa-color-primary: '@{var}-color';
}

// Starting the PA mixin
.pacolors() {
  // Generating the loop for each PA
  .for(@pas); .-each(@name) {
    // After loop happens, it checks what brand is being called
    .define(@name);
    .@{name} .bg-accent {
        background-color: @@pa-color-primary;
    }
  }
}

.pacolors();

Any help would be appreciated.

回答1:

You can achieve this by using the built-in contrast function provided by LESS.

// Starting the PA mixin
.pacolors() {
  // Generating the loop for each PA
  .for(@pas); .-each(@name) {
    // After loop happens, it checks what brand is being called
    .define(@name);
    .@{name} .bg-accent {
        background-color: @@pa-color-primary;
          color: contrast(@@pa-color-primary,
                          lighten(@@pa-color-primary, 100%),
                          darken(@@pa-color-primary, 100%),10%);  
          /* syntax - contrast(color-for-comparison,
                               color1 - lighten (100%) is essentially white,
                               color 2 - darken (100%) is essentially black,
                               threshold percentage based on which decision is taken
           */
    }
  }
}

Demo | LESS Function Spec - Contrast

Simplified Version: (Courtesy - seven-phases-max)

// Colors
@pas:
    pa1 #72afb6,
    pa2 #9fad9f,
    pa3 #8dd8f8,
    pa4 #00567A;

// Styles
& {
    .for(@pas); .-each(@pa) {
         @name:  extract(@pa, 1);
         @color: extract(@pa, 2);
        .@{name} .bg-accent {
            background-color: @color;
              color: contrast(@color, white, black, 10%);        
        }
    }
}

p {padding: 10px}

// ........................................................

@import "https://raw.githubusercontent.com/seven-phases-max/less.curious/master/src/for";

Demo 2



标签: less contrast