I'm trying to create a mixin within LESS that will use it's selector name as a variable inside of the mixing. The mixin should look something like this, but I cannot find the exact syntax for it or if it's even possible:
.bg{
background-image: url('images/@{SELECTORNAME}.png');
}
#header{
.bg;
}
results in:
#header{
background-image: url('images/header.png');
}
I'm thinking this isn't possible, plus what would happen if the selecter was something like:
div#menu ul li
That wouldn't really work but perhaps anyone knows of an alternative, wether this is possible in any other preprocessor.
Thank you!
Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.
LESS allows variables to be defined with an @ symbol. The Variable assignment is done with a colon(:).
However, you can build the selector in conjunction to linking with the file name in a mixin, something like so:
LESS
.buildSelectorConnection(@selectorName, @pre: ~'') {
@{pre}@{selectorName} {
background-image: url('images/@{selectorName}.png');
}
}
.buildSelectorConnection(header, ~'#');
.buildSelectorConnection(do-a-class, ~'.');
CSS Output
#header {
background-image: url('images/header.png');
}
.do-a-class {
background-image: url('images/do-a-class.png');
}
However, it would take quite a bit more logic, decision making on your part, and some javascript coding in LESS if you wanted to make such a thing be able to handle something like div#menu ul li
where the actual filename generated was something like div-menu-ul-li.png
.
Something like this could be done:
LESS
.buildSelectorConnection(@selectorName, @pre: ~'', @post: ~'') {
@{pre}@{selectorName}@{post} {
background-image: url('images/@{selectorName}.png');
}
}
.buildSelectorConnection(menu, ~'div#', ~' ul li');
CSS Output
div#menu ul li {
background-image: url('images/menu.png');
}
This basically lets you build any selector string, but the file name itself will only be that initial selector passed in, which needs to be something valid for a file name.
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