Sass mixin to prepend to selector

可紊 提交于 2019-12-23 15:16:44

问题


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');
  }
}


来源:https://stackoverflow.com/questions/19563128/sass-mixin-to-prepend-to-selector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!