Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass: Using Ampersand '&' for body tag which has a specific class

Tags:

css

sass

Demo: https://codepen.io/moradxd/pen/WJpPyQ

Assume i have this HTML code:

<body class="boxed">
  <div class="text-white">
    <a href="#" class="btn-featured">Button</a>
  </div>
</dody>

I'm using this sass code as following:

.boxed {
  // error with using "Ampersand"
  body& {

  }
}

But it results a compiling error which says:

enter image description here

Although the result i want is as following:

// This the result i want
body.boxed {

}

I know that i can use it like this, and it will result what i'm looking for:

// I know i can use this
body {
  &.boxed {

  }
}

But i want to separate the .boxed class code from inside the body css code for orgnization purpose.

So why this is not allowed although the similar code for element and it's parent is working for the following:

// Although this similar code for element and 
// it's parent is working
.btn-featured {
  .text-white & {
    font-size: 30px;
  }
}

In fact i hope to know why this not allowed!

like image 299
Morad Hamdy Avatar asked Dec 02 '25 00:12

Morad Hamdy


1 Answers

Hello morad you need to use @at-root

.boxed {
  @at-root body#{&} {
     color: red;
  }
}

codepen

like image 182
patelarpan Avatar answered Dec 03 '25 17:12

patelarpan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!