0

I would like to take advantage of the name of my css classes to also specify the url for an image that they depend on. I'm aware that using an ampersand within a selector allows you to add additional states but I was wondering if I can access it as a string? I would like to do something like the following:

.my-image{
    background: url('images/@{&}.png');
}

and have it compile to:

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

On second thought, I now see I would also need to remove the leading period somehow, but regardless - is there a way to capture the selector name as a string inside the property definitions?

RutledgePaulV
  • 2,568
  • 3
  • 24
  • 47

1 Answers1

1

Ok this isn't exactly how you imagined it, but maybe it solves your problem.

Create an array with all the values of the selectors you want, then let the compiler create the rule (I've found the code here):

@images: 'my-image', 'cool-image', 'foobar';

.-(@i: length(@images)) when (@i > 0) {
    @name: e(extract(@images, @i));
    &.@{name} {background: url("images/@{name}.png")}
    .-((@i - 1));
} .-;
Community
  • 1
  • 1
JohnKiller
  • 2,008
  • 18
  • 28
  • 1
    Thanks John, that is indeed a valid option and something I didn't think of. I'm still curious if there's a way to access the current context somehow so I'm going to leave the question open but if nothing turns up I'll accept it :) – RutledgePaulV Nov 30 '14 at 18:26
  • 1
    Btw., you don't need quotes there, `@images: my-image, cool-image, etc;` is valid Less statement and then you don't need `e(...)`. – seven-phases-max Nov 30 '14 at 19:56