Jona
Jona

Reputation: 305

css less adding a variable to the selector

I'm a LESS newbie just trying to use it initally to remove some duplication form my stylessheets. I'm trying to add a variable to a (relatively) complex selector in less 1.2.21 using the following code:

@current_house_id: 97;
ul#house-family-menu li#menu-item-@current_house_id {
    background: #8cb4e8 url(images/family-current.png) no-repeat 97% 50%;
}

For the avoidance of doubt the original css would have been:

ul#house-family-menu li#menu-item-97 {
    background: #8cb4e8 url(images/family-current.png) no-repeat 97% 50%;
}

When I compile this with lessc I get error:

Syntax Error: on line 268: expected one of [ ( . # * - :: : @media @font-face , { ; got @ after: ul#house-family-menu li#menu-item-

I've tried various escaping mechanisms suggested here and elsewhere but nothing seems to work, perhaphs this isn't supported in less? If it isn't I guess I could do the less equivlent of a case on ul#house-family-menu li#menu-item and apply the items one at a time?

Any help much appreciated.

Upvotes: 2

Views: 1710

Answers (1)

Patrick
Patrick

Reputation: 3498

The following:

@b: 3;

(~'.tester@{b}') {
    font-size: 20px;
}

Outputs:

.tester3 {
    font-size: 20px;
}

Your solution:

@current_house_id: 97;
(~'ul#house-family-menu li#menu-item-@{current_house_id}') {    }

Outputs:

ul#house-family-menu li#menu-item-97 {    }

Edit:

1.4.0-beta looks to have changed this (http://lesscss.org/):

(~".myclass_@{index}") { ... 

selector interpolation is deprecated, do this instead

.myclass_@{index} { .... 

Additionally:

You cannot do selector interpolation, as expected (v1.5.0 at least), if selector is a pseudo element. Open issue: https://github.com/less/less.js/issues/1294

Work around:

.myMixin(@whichPseudo) {
  @pseudo-selector: ~":@{whichPseudo}";
    &@{pseudo-selector} {
       background: red;
    }
}

#someEl1 {
    .myMixin(before);
}

#someEl2 {
   .myMixin(after);
}

Upvotes: 3

Related Questions