user3006927
user3006927

Reputation: 476

SASS how can I add a class to a tag using the ampersand?

How can I write these sass declarations so that it compiles to a.btn_primary_cancel

I tried this but it's not working:

.btn_primary_cancel {

  a& {
    line-height: 4rem;
  }

}

Upvotes: 3

Views: 1780

Answers (3)

Jinu Kurian
Jinu Kurian

Reputation: 9416

Yes !! You can have the desired result. Just use @at-root

Try this code.

.btn_primary_cancel {
  @at-root a#{&} {
    line-height: 4rem;
  }
}

it will compile to

a.btn_primary_cancel {
  line-height: 4rem;
}

See this in action - CODEPEN

Upvotes: 3

Sérgio Carneiro
Sérgio Carneiro

Reputation: 3966

If you wrap the ampersand in #{&} will work, but not as you think.

Because it is within the class declaration, it will create the following:

.btn_primary_cancel {
  a#{&} {
    line-height: 4rem;
  }
}

Outputs to:

.btn_primary_cancel a.btn_primary_cancel {
  line-height: 4rem;
}

This said, I don't think you can do what you are requesting. The CSS hierarchy simply doesn't work that way.

Upvotes: 0

cnorthfield
cnorthfield

Reputation: 3501

It should be:

a {
  &.btn_primary_cancel {
    line-height: 4rem;
  }
}

Which will compile to:

a.btn_primary_cancel {
  line-height: 4rem;
}

Upvotes: 2

Related Questions