Reputation: 117
Is there a way where I could dynamically add the styles in css/less file by just passing in class name ?
For example:
<div class="xyz_20"></div>
<div class="xyz_40"></div>
Instead of writing:
.xyz_20 {width:20px;} .xyz_40 {width:40px;}
Is there a way where i could write a single class .xyz_i and width be automatically added based on the i value, like .xyz_i {width: i px;}` without involving javascript.
If so, Please suggest.
Upvotes: 2
Views: 2127
Reputation: 4604
This is not possible, as far as I know, however this is a great use case for inline styling:
<div class="xyz" style="width:20px"></div>
If you wanted to support a finite number of widths, then you can use recursion to generate classes:
.widthgen(@count) when (@count > 0) {
.widthgen((@count - 10));
.xyz_@{count} {
background-color: red;
width: @count * 1px;
}
}
.widthgen(50);
Output:
.xyz_10 {
background-color: red;
width: 10px;
}
.xyz_20 {
background-color: red;
width: 20px;
}
.xyz_30 {
background-color: red;
width: 30px;
}
.xyz_40 {
background-color: red;
width: 40px;
}
.xyz_50 {
background-color: red;
width: 50px;
}
You could use the lists
plugin (to install: npm install -g less-plugin-lists
) if your widths you want to support are not easily captured in a linear pattern:
@widths: 10, 20, 40, 50;
.for-each(@i in @widths) {
.xyz_@{i} {
background-color: red;
width: @i * 1px;
}
}
You would compile that with:
lessc --lists in.less out.css
And you would get:
.xyz_10 {
background-color: red;
width: 10px;
}
.xyz_20 {
background-color: red;
width: 20px;
}
.xyz_40 {
background-color: red;
width: 40px;
}
.xyz_50 {
background-color: red;
width: 50px;
}
Upvotes: 3
Reputation: 2235
No.
There is no way to write classes and expect the browser to infer meaning from them.
The only way to accomplish something similar to this would be with javascript (which OP said they did now want to use).
Upvotes: 0