5

I need to support old and new declarations of pseudo elements on the project I am working on. I am wanting to create an SCSS @mixin that saves me from having to repeat myself.

I'm wanting to achieve the following:

Declaration:

.selector {
  &#{$before} {
    content: '';
  }
}

Compiled:

.selector:before { content: ''; }
.selector::before { content: ''; }

So I essentially need the @mixin to @extend any css properties that follow for both :before and ::before.

I have searched high and low, without coming across a solution for this. Are their any Sass wizards able to make my dreams a reality?

Thank you in advance

DanMad
  • 1,643
  • 4
  • 23
  • 58

1 Answers1

6

Here you go bud:

@mixin pseudo-element($element) {
  &:#{$element}, &::#{$element} {
    @content;
  }
}

// Usage:

.foo {
  @include pseudo-element('before') {
    content: '';
  }
}

Output:

.foo:before, .foo::before {
  content: '';
}

CodePen: https://codepen.io/esr360/pen/VzVBpj

ESR
  • 1,669
  • 1
  • 18
  • 22
  • Hi. Wow! For some reason I have missed the `@content` SCSS declaration in my learning. This changes everything (again). Only thing I changed was the fact that you separated each pseudo element with a comma, my understandings is that they need to be separate so browsers that don't recognise `::before` won't also ignore `:before`: https://codepen.io/anon/pen/MvzBmL. Thanks for this. – DanMad Aug 30 '17 at 05:17
  • No worries! Yes you are right to make the change you did, I had forgotten there are issues around using both combined with a comma (reference: https://stackoverflow.com/a/10181948/2253888) – ESR Aug 30 '17 at 05:21
  • Cheers for the confirmation. Much appreciated. – DanMad Aug 30 '17 at 05:21