Search code examples
sasssiblings

Is it possible to concatenate two siblings without parent in Sass?


What I want is concatenate two child inside the parent but without choosing the parent on output.

What I mean is here:

.parent {
  .child {
    color: green;
    & + & {
      margin-top: 6px;
    }
  }
}

On the output I have this:

.canvas-btn .canvas-btn__icon + .canvas-btn .canvas-btn__icon {margin-top: 6px;}

but if it's possible to make the next way without duplicating the code is Sass?

.canvas-btn .canvas-btn__icon + .canvas-btn__icon {margin-top: 6px;}


Solution

  • You need to use the parent selector (&) as a variable here and treat it like the list of lists that it is:

    @function nest-adjacent-selector($sel) {
        $new-sel: ();
        @each $s in $sel {
            $last: nth($s, -1);
            $new-sel: append($new-sel, $s #{'+'} $last, comma);
        }
        @return $new-sel;
    }
    
    .parent {
        .brother, .sister {
            color: green;
            @at-root #{nest-adjacent-selector(&)} {
                margin-top: 6px;
            }
        }
    }
    

    Output:

    .parent .brother, .parent .sister {
      color: green;
    }
    .parent .brother + .brother, .parent .sister + .sister {
      margin-top: 6px;
    }
    

    Note that this will not work if you're using certain versions of LibSass. For more information on how this works, see this question.