Use selector name as variable in LESS mixin

I am trying to create a mixin inside LESS that will use this selector name as a variable inside the mix. The mixin should look something like this, but I cannot find the exact syntax for it, or even this is possible:

.bg{ background-image: url('images/@{SELECTORNAME}.png'); } #header{ .bg; } 

leads to:

 #header{ background-image: url('images/header.png'); } 

I think this is not possible, plus what will happen if the selector is something like:

 div#menu ul li 

This does not work, but maybe someone knows about the alternative, so this is possible in any other preprocessor.

Thanks!

+7
source share
2 answers

You cannot "read" the name of the selector.

However, you can create a selector in combination with a link to the file name in mixin, something like this:

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, you will need a bit more logic, decision making on your part and some javascript codes in LESS if you want this thing to be able to handle something like div#menu ul li , where the actual file name was something like div-menu-ul-li.png .

Nevertheless...

Something like this can 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 allows you to create any selector line, but the file name itself will only consist of the initial selector passing, which should be something valid for the file name.

+14
source

Yes, LESS just introduced an advanced feature in 1.4.0.

See the answer to this question here: Does LESS have an extension "feature?

0
source

All Articles