Search code examples
.netcsslessdotless

less function to fade pre-determined div background


Background / Goal

I some divs. On each of these divs, I'd like to place two different classes (each of which have different logical meanings within my app).

I would like one class to represent a level, which would translate into the color of the div. I would like another class to represent distance, and control a fade level of whatever background is applied.

So I would like the div to look like:

<div class="element level-beginner distance-long">

And would like that to translate into, say, a green background that is faded.

I know a little bit about LESS (but only a little bit), and don't this seems like a case where nested styles would help (because it doesn't deal with a child element but rather whether a certain class has already been applied).

Essentially, I'd like to control the color and the opacity/fade as CSS classes that are independent of each other.

Question

  • Is there a way to utilize less so that a class will control the alpha/fade of the background of a div element without having to specify the color as well?

Solution

  • The LESS color opacity functions (fadein, fadeout, fade) require a color as their first argument. LESS has no idea how you're going to combine your classes, so it doesn't know where to get the color from.

    There is an opacity property in CSS, but it adjusts the transparency of the entire element (including the text).

    Your only real option is to write out selectors for each combination you're planning to use or have a mixin that will generate them for you:

    .themeMatrix(@color) {
        &.styleA {
            background: fade(@color, 50%);
        }
    
        &.styleB {
            background: fade(@color, 20%);
        }
    
        &.styleC {
            border: 1px solid @color;
        }
    }
    
    .colorA {
        .themeMatrix(white);
    }
    
    .colorB {
        .themeMatrix(green);
    }