Search code examples
csssassmixinsscss-mixins

sass mixin + it-self as consecutive tag?


I'm looking for a way to make an equivalent to .bloc + .bloc or .article + .article but directly from a mixin bloc-article() :

@mixin bloc-article() {

    margin-top: 20px;
    margin-top: 50px;

    & + "bloc-article()" { // is there a "$this"-like to make an equivalent to `.bloc + .bloc` or `.article + .article` here ?
        border-top: 1px solid red;
    }
}

.bloc {
    @include bloc-article();
}

.article {
    @include bloc-article();
}

is there a "$this"-like to make an equivalent to .bloc + .bloc or .article + .article directly from the mixin ?


Solution

  • You can write your mixin with an & + & selector:

    @mixin bloc-article() {
      // …
    
      & + & {
        border-top: 1px solid red;
      }
    }
    

    Which compiles from:

    .article {
      @include bloc-article();
    }
    

    to:

    .article + .article {
      border-top: 1px solid red;
    }
    

    Here, the Sass parent selector is the $this you are looking for.

    From the docs:

    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.