I am working on a project with multiple sections. Depending on the section, elements in that section have varying colors. Through my LESS files I am defining all these possibilities like so:
a{
.section_what &{
color: darken(@what,10%);
}
.section_where &{
color: darken(@where,10%);
}
.section_who &{
color: darken(@who,10%);
}
.section_post &{
color: darken(@post,10%);
}
.section_events &{
color: darken(@events,10%);
}
.section_deals &{
color: darken(@deals,10%);
}
}
It seems like this is not the most streamlined way of doing things. Using this method I have to repeat this list of sections quite a bit. So every element that is altered by its section requires this list of sections defined. Sometimes its color, background-color, border-color etc...
Is there a better way?
In LESS you can get it with more generic code like this:
@what: #111;
@where: #222;
@who: #333;
@post: #444;
@events: #555;
@deals: #666;
@items: what,
where,
who,
post,
events,
deals;
@items-count: 6;
.sections() {
.-(@items-count);
.-(@i) when (@i > 0) {
.-((@i - 1));
@name: extract(@items, @i);
.section_@{name} & {
color: darken(@@name, 10%);
}
}
}
a {
.sections();
}
b {
.sections();
}
Or, if you don't need those variables for anything else, even better:
@items: what #111,
where #222,
who #333,
post #444,
events #555,
deals #666;
.sections() {
.-(length(@items));
.-(@i) when (@i > 0) {
.-((@i - 1));
@item: extract(@items, @i);
@name: extract(@item, 1);
.section_@{name} & {
color: darken(extract(@item, 2), 10%);
}
}
}
a {
.sections();
}
b {
.sections();
}
It looks quite verbose but I suppose a level of customization worths this.
Note that length
function is available only in LESS 1.5.x, for earlier versions you can use a predefined count variable as in the first example.
And yet another approach (if you prefer "copy-paste" style):
@what: #111;
@where: #222;
@who: #333;
@post: #444;
@events: #555;
@deals: #666;
.item(@name) {
.section_@{name} & {
color: darken(@@name, 10%);
}
}
a {
.item(what);
.item(where);
.item(who);
.item(post);
.item(events);
.item(deals);
}
P.S.
So every element that is altered by its section requires this list of sections defined. Sometimes its color, background-color, border-color etc...
It is also possible to add more "customization points" for properties as well - but it depends on how exactly those sections and CSS properties tie to each other... (So I did not put that into examples above to not make things even more complicated to understand).
Basically the key is "list/loops", "mixins/abstraction" etc.