Hover color cross-site for each color

117 views Asked by At

If I have the following variable:

@text-c: #cccccc;

Is there a way to specify the hover variant of the color (in this case the colour #aaaaaa) so it applies cross-site, without having to add it in each separate :hover rule?

2

There are 2 answers

1
seven-phases-max On BEST ANSWER

Mixin and extend are probably what you're looking for. The variable itself does not say yet how or where you use it (be it either for some color property or not) or if you use it at all. So instead of relying on some indirect logic, as there's no way for compiler to guess to insert :hover {color: #aaaaaa} for every element that has color: #cccccc, first of all because :hover "sub-style" is not inherited across elements like properties do (e.g. what if you just set body {color: @text-c}?), make it explicit, e.g. (not optimized variant just to illustrate the method):

// "color team"
.text-c() {
    color: #cccccc;
    &:hover {color: #aaaaaa}
}

// usage 

div.zoo {
    .text-c();
}

span.park {
    .text-c();
}

td#life {
    .text-c();
}

// etc.

An actual optimized (most likely extending some template instead of copying the same properties every time) would depend on how/where/how-often/etc. you're going to use it and (not-less-important) how (and if) you plan it to be customized (for example see @Harry's answer on how to make a generic mixin instead of color-value-hardcoded like I did above).

0
Harry On

If you just want the variable value to be set in one common place instead of at multiple locations, you could create another variable and use the darken function to obtain the hover variant of it.

Below is a sample snippet for this.

@text-c: #cccccc;
@text-c-hover: darken(@text-c, 13.5%);

a{
    color: @text-c;
    &:hover{
        color: @text-c-hover;
    }
}

On the other hand if you want to write the hover selector itself at only one place then you can use a mixin with the parent selector (&) and invoke it all relevant places like in the below snippet. This will set the hover text color for the element as 13.5% darker the default text color.

.hover(@input){
    &:hover{
        color: darken(@input, 13.5%);
    }
}

#demo{
    @color: #aaaaaa;
    color: @color;
    .hover(@color);
}