7

Here's what i have in my CSS file ...

.search-doctors-box {
    position: relative;
    z-index: 999;
    margin: 0px;
}

.search-doctors-box--at-map {
    position: absolute;
    margin-bottom: 10px;
    top: 0px;
    left: 415px;
    width: 680px;
}

I want to achieve this in SASS using the & as the parent selector name and to join it with the rest of the string...

.search-doctors-box {
    position: relative;
    z-index: 999;
    margin: 0px;

    &--at-map {
        position: absolute;
        margin-bottom: 10px;
        top: 0px;
        left: 415px;
        width: 680px;
    }
}

Is it possible?

Thanks!

Darren Shewry
  • 10,179
  • 4
  • 50
  • 46
Kitze
  • 709
  • 3
  • 8
  • 21

1 Answers1

16

Unfortunately there are limitations to what you can use in combination with the ampersand in selectors - it expects a class name (.), an id (#), a pseudo class (:), or attribute selectors ([]).
Other acceptable symbols that can also be combined with & are valid CSS selector combinators , >, +, and ~.


Solution for Sass >= 3.3:

You can use string interpolation on the ampersand #{&} and then you can concatenate it with any string.
However, this way (if you do this in a nested rule) a nested selector still automatically gets the parent selectors attached at the beginning:

.parent {
  #{&}--at-map { ... }
}

would return:

.parent .parent--at-map { ... }

But, you can save the contents of the ampersand in a variable and use it outside the parent rule. So in your case something along these lines could work:

$last-rule: null;
.search-doctors-box {
  position:relative;
  z-index:999;
  margin: 0px;
  $last-rule: &;
}
#{$last-rule}--at-map {
  position: absolute;
  margin-bottom:10px;
  top: 0px;
  left: 415px;
  width:680px;
}

DEMO

or even better, you could use

@at-root

with nested concatenated selectors, like so:

.search-doctors-box {
  position:relative;
  z-index:999;
  margin: 0px;

  @at-root #{&}--at-map {
    position: absolute;
    margin-bottom:10px;
    top: 0px;
    left: 415px;
    width:680px;
  }
}

which will give you the desired output:

DEMO

Martin Turjak
  • 20,896
  • 5
  • 56
  • 76
  • 1
    Your first example doesn't work in the stable version of Sass. If you're showing off upcoming features, you need to make this clear in your answers. – cimmanon Dec 11 '13 at 13:07
  • +1 for telling me something I didn't know about SCSS. – Ennui Dec 11 '13 at 13:28
  • @cimmanon thanks ... I'm using the prerelease (v3.3) ... and then I forget that the stable version still lacks some of the features. I made it clear in the answer now. – Martin Turjak Dec 11 '13 at 13:31
  • 1
    @Kitze I added an additional option for Sass >= 3.3 that gives you basically exactly what you want. – Martin Turjak Dec 22 '13 at 22:05
  • Any idea of when the first option listed in this answer will work? It is a much tidier solution than the others. Thanks for the answer here though, it was very useful! – theorise Jun 22 '14 at 15:31