Lighten color from parent in Less

2019-03-22 10:45发布

问题:

I am starting out with Less and one of the reasons I wanted to is because of the ligthen() function. So my first attempt was to do something with that.

This is my HTML

<div class="box blue">
    <div class="boxbar">Foo</div>
    blue
</div>

I finally got it working, but I doubt it's supposed be like this:

@blue:   #468ACE;
@green:  #41A53D;
@red:    #9C2525;
@purple: #8938BF;

div 
{
    padding: 10px;
}

.blue { 
    background-color: @blue; 
    .boxbar { background-color: lighten(@blue, 10%); }
}
.green { 
    background-color: @green; 
    .boxbar { background-color: lighten(@green, 10%); }
}
.red { 
    background-color: @red; 
    .boxbar { background-color: lighten(@red, 10%); }
}
.purple { 
    background-color: @purple; 
    .boxbar { background-color: lighten(@purple, 10%); }
}

.boxbar 
{
    height: 10px;
}

How can I refactor this? Surely it must be easier to say "get your parent color, and lighten it a bit". I tried a couple of things: inherit (was worth a shot!), have the lightened versions inside .boxcar. But this obviously compiled to .boxcar .blue.. which is not what I want and I ended with what you can see here.. it works.. but it doesn't feel right. Then I would need to write code for every new color I introduce..

回答1:

I am not completely sure what your desired solution would be ... but maybe something like making a mixin would help you from having to write so much stuff out.

LESS:

.bgmixin(@color) {
    (~".@{color}") {
        background-color: @@color;
        .boxbar {
            background-color: lighten(@@color, 10%);
        }
    }
}

@blue: #468ACE;
@green: #41A53D;
@red: #9C2525;

.bgmixin("blue");
.bgmixin("green");
.bgmixin("red");

CSS:

.blue{
  background-color: #468ace;
}
.blue .boxbar {
  background-color: #6ea3d9;
}
.green{
  background-color: #41a53d;
}
.green .boxbar {
  background-color: #59c055;
}
.red{
  background-color: #9c2525;
}
.red .boxbar{
  background-color: #c52f2f;
}

Update:

In LESS>=1.4 you would want to use something like this to interpolate the class name from the color name:

.bgmixin(@color) {
    @classname: ~"@{color}"; 
    .@{classname} {
        background-color: @@color;
        .boxbar {
            background-color: lighten(@@color, 10%);
        }
    }
}


标签: less