Sass mixin to prepend to selector

2019-06-24 02:23发布

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?

标签: sass mixins
1条回答
虎瘦雄心在
2楼-- · 2019-06-24 03:19

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');
  }
}
查看更多
登录 后发表回答