Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less - using classes created inside guarded mixins

Tags:

css

less

I have the following less code:

.loop (@index) when (@index >= 10) {
  (~".font@{index}") {
    font-size: ~"@{index}px";
  }
  .loop(@index - 1);
} 
.loop (0) {}
.loop (10);

which output:

.font15 {
  font-size: 15px;
}
.font14 {
  font-size: 14px;
}
.font13 {
  font-size: 13px;
}
.font12 {
  font-size: 12px;
}
.font11 {
  font-size: 11px;
}
.font10 {
  font-size: 10px;
}

In the end of the Less document I have this class:

.title{
    font-size:14px;
    margin-bottom:0.5em;
    .font13;
}

I'm using WinLess to compile it and I get an error saying the ".font13" is undefined Is there any way to use a class defined "dynamically" in the same document?

Thanks!

like image 245
Matan Hafuta Avatar asked Jul 02 '13 09:07

Matan Hafuta


People also ask

What is a less mixin?

Mixins in LESS, are a way to include a bunch of CSS properties from one ruleset to another i.e multiple times in the same file.

What does the special variable @arguments do in a less mixin?

Additionally, LESS has a special variable named @arguments which will pass the default values all together.

What is CSS mixin?

The @mixin directive lets you create CSS code that is to be reused throughout the website. The @include directive is created to let you use (include) the mixin.


1 Answers

Unfortunately. The selector interpolation is just string interpolation, and the string gets then printed into CSS, so no class object is generated in the Less run.

So the best way to do something like this would be to design a getter mixin (that you can call from other rules) and maybe a generator mixin (that writes the .font10, .font11, ... .fontNN classes) ... the later is not necessary if you want to generate the classes only in the loop (and you can just merge it with the loop).

Something like this:

.getFont(@size) { font-size: ~"@{size}px"}

.genFontClass (@size) {
   (~".font@{size}") { .getFont(@size); }
}

and then you can use your loop to generate the .fontNN classes:

.loop (@index) when (@index >= 10) {
    .genFontClass (@index);
    .loop(@index - 1);
} 
.loop (@index) when (@index < 10) {}

using for example index 13:

.loop (13);

with output CSS:

.font13 {
  font-size: 13px;
}
.font12 {
  font-size: 12px;
}
.font11 {
  font-size: 11px;
}
.font10 {
  font-size: 10px;
}

and independently from this generated classes that got printed directly to the output CSS (and are inaccessible from other Less rules), you can call the getter mixin, to add desired properties to your rules, in our example the font for the desired index 13:

.title{
    margin-bottom:0.5em;
    .getFont(13);
}

which will now add the font size property to the .title rule.

CSS:

.title {
  margin-bottom: 0.5em;
  font-size: 13px;
}

Hope this helps.

like image 52
Martin Turjak Avatar answered Sep 23 '22 22:09

Martin Turjak