Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in SASS, post selector ampersand doesnt work when used in a nested structure

Tags:

css

sass

my markup is let's say:

<div class="container marker">
  <div class="parent">
    <div class="child">
      content
    </div>
  </div>
</div>

and my scss would be

.container {
  .parent {
    .child {
      .marker & {
        background: red;
      }
    }
  }
}

As long as I put the child styling nested in parent's with the marker class, the ampersand (&) rule doesn't engage. but if i write:

.parent {
  .child {
    .marker & {
      background: red;
    }
  }
}

everything seems fine. why? what am I missing?

example in CodePen: http://codepen.io/anon/pen/GgRvOV

like image 704
user2520818 Avatar asked Nov 14 '14 09:11

user2520818


People also ask

What does the ampersand & symbol do in Sass SCSS?

Ampersand or “&” is a powerful feature of SASS. It enhances the readability of code by using nesting statements, which takes an edge over conventional CSS. We can nest the css class any number of times but most of the times it's not required.

What are the nested rules in sass?

Description. Nesting is combining of different logic structures. Using SASS, we can combine multiple CSS rules within one another. If you are using multiple selectors, then you can use one selector inside another to create compound selectors.

What selector nesting in Sass is used for?

Contents. The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.

What is the use of & in SCSS?

The & is a special selector invented by SCSS which is used in nested selectors to refer to the outer selector . It simply means that it will be replaced with the outer selector when compiling to CSS.


2 Answers

Because the output of your sass would be:

.marker .container .parent .child {
  background: red;
}

Because you are telling the sass to output .marker & which is saying this is the parent of this chain, so .container is being treat as the first child of .marker.

You need to do:

.parent {
  .child {
    .container.marker & {
      background: red;
    }
  }
}

Which will output the vanilla CSS:

.container.marker .parent .child {
  background: red;
}

A great tool to help you understand how you sass outputs is http://sassmeister.com/

like image 93
Jon Kyte Avatar answered Oct 21 '22 08:10

Jon Kyte


Other alternative is by using variable(s) and SASS’s Interpolation Syntax, using this will keep your original nesting

.container {
  $c: &;    // store parent into variable
  .parent {
    .child {      
      #{$c}.marker & {
        background: red;
      }
    }
  }
}

output:

.container.marker .container .parent .child {
  background: red;
}
like image 3
Windo Avatar answered Oct 21 '22 07:10

Windo