Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use selector name as variable in LESS mixin

Tags:

css

less

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!

like image 832
Milanzor Avatar asked Jun 21 '13 12:06

Milanzor


People also ask

What is the correct way to define a mixin in LESS?

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.

What is the correct syntax of a variable in LESS?

LESS allows variables to be defined with an @ symbol. The Variable assignment is done with a colon(:).


1 Answers

You cannot "read" the selector name.

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.

Nevertheless...

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.

like image 132
ScottS Avatar answered Oct 21 '22 14:10

ScottS