sapphyra
sapphyra

Reputation: 77

scss continue name with interpolation and `@at-root`

I am trying to fully understand the ampersand (&) and interpolation operators in sass, while also following bem. For example, I have a table block declared like so:

.table {
  width: 60%;
  &__title {
    // omit code
  }
  &__data {
    display: grid;
    width: 100%;
    & > #{@at-root}__key + #{@at-root}__value > * { // <- ISSUE HERE
      // give all direct, non text child nodes margin below
      margin-bottom: 0.5em;
    }
  }
}

and used like:

<div class='table'>
  <div class='table__title'>...</div>
  <div class='table__data'>
    <div class='table__key'>...</div>
    <div class='table__value'>...</div>
  </div>
</div>

See line 9 of the sass; here the expected compiled result would be

.table__data > .table__key + .table__value > * {
  margin-bottom: 0.5em;
}

but of course @at-root is not a variable so an error is thrown

SassError: Invalid CSS after "@": expected expression (e.g. 1px, bold), was "@at-root}__key + #{"

Does anything like my attempt exist, can/should I somehow combine the @at-root element with classes I'm using?

Articles I've already tried:

EDIT made the question clearer

Upvotes: 1

Views: 267

Answers (1)

Chris W.
Chris W.

Reputation: 23280

What I do when I actually deem this necessary is to just create your reference from the root. It's kind of like the old days when you often had to declare that = this scenarios (well not really but you get the idea lol).

However, generally I avoid this kind of deep nesting unless it's genuinely required to avoid too many levels of specificity (habit from the old days when such noticeably things effected performance.

See example below, and a codepen to tinker

.table {
  $root: &; // <-- create reference to root that allows interpolation.
  width: 60%;
  &__title {
    // omit code
  }
  &__data {
    display: grid;
    width: 100%;
    & > #{$root}__key + #{$root}__value > * { // <- ISSUE HERE
      // give all direct, non text child nodes margin below
      margin-bottom: 0.5em;
    }
  }
}

...and the compiled output...

.table {
  width: 60%;
}
.table__data {
  display: grid;
  width: 100%;
}
.table__data > .table__key + .table__value > * {
  margin-bottom: 0.5em;
}

Upvotes: 2

Related Questions