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!
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.
Additionally, LESS has a special variable named @arguments which will pass the default values all together.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With