Ampersand (&) as a variable inside SASS @mixin

Issue

Looking up Bootstrap 5 code, I faced this following statement on bootstrap/scss/mixins/_forms.scss file:

@mixin form-validation-state-selector($state) {
  @if ($state == "valid" or $state == "invalid") {
    .was-validated #{if(&, "&", "")}:#{$state},
    #{if(&, "&", "")}.is-#{$state} {
      @content;
    }
  } @else {
    #{if(&, "&", "")}.is-#{$state} {
      @content;
    }
  }
}

And could not exactly understand the usage of & variable inside the #{if(&, "&", "")} statements. How is it working?

I know the Ampersand (&) character is used, os SASS, to include the parent selector(s), when writing on an indented hierarchy. But I couldn’t guess how it has been using on the mentioned statement inside the @mixin, when out of quotes ".
Can someone explaning it?

Thanks in advance!

Solution

They are using interpolation for part of the selector with the #{if(&, "&", "")}:#{$state} logic.

The if() function works like if(val, res1, res2) where if val is true then res1 is used, else res2, like a ternary. So if the & was truthy e.g. parent selector exists, then it would churn out .was-validated &:valid, using "&", otherwise it would be .was-validated :valid using the empty string.

Here is a CodePen demo which demonstrates the #{if(&, "&", ""} usage.

Answered By – Tanner Dolby

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published