Sass mixin to prepend to selector

2019-06-24 02:54发布

问题:

Is it possible to make a SASS mixin to prepend its output to the selector? I use Modernizr to check for svg capability of the browser. It outputs the svg class to the <html> element when svg is supported.

I would like the background-image to change depending on the svg capability. Basically, this is what I need:

.container .image { background-image: url('some.png'); }
html.svg .container .image { background-image: url('some.svg'); }

What I would like to have in my SCSS is a mixin that I could @include in the following way:

.container {
  .image {
    background-image: url('some.png');
    @include svg-supported {
      background-image: url('some.svg');
    }
  }
}

Instead of having to write:

.container {
  .image {
    background-image: url('some.png');
  }
}

@include svg-supported {
  .container {
    .image {
      background-image: url('some.svg');
    }
  }
}

Is this possible somehow?

回答1:

Found the answer here.

It is possible by using the ampersand & sign. For reference, the needed mixin in this case is

@mixin svg-supported {
  html.svg & {
    @content;
  }
}

This can be used in the following way:

.image {
  background-image: url('some.png');
  @include svg-supported {
    background-image: url('some.svg');
  }
}


标签: sass mixins