SASS: content block mixin (or placeholder) that takes contextual selectors and appends them to selector in mixin

与世无争的帅哥 提交于 2019-12-08 07:02:45

问题


I want to do something like this:

@mixin context($size) {
  body.#{$size} {
    @content
  }
}

div {
  span {
    font-size: 2em;
    @include context('large') {
      & {
        font-size: 5em;
      }
    }
  }
}

To produce:

div span {
  font-size: 2em;
}

body.large div span {
  font-size: 5em;
}

What it ACTUALLY (predictably) produces:

div span {
  font-size: 2em;
}

div span body.large {
  font-size: 5em;
}

I could just replicate the selectors inside different mixins, but given that selectors could be complex that's a lot of extra junk:

@include context('large') {
  div {
    span {
      font-size: 5em;
    }
  }
}

I could make the selectors into mixins so I don't have to repeat them each time, but...

Isn't there a way to use placeholders, maybe in combination with mixins, to get what I want in the first two code blocks above?


回答1:


You just need to move the & to be part of the mixin:

@mixin context($size) {
  body.#{$size} & {
    @content
  }
}

div {
  span {
    font-size: 2em;
    @include context('large') {
        font-size: 5em;
    }
  }
}

Output:

div span {
  font-size: 2em;
}

body.large div span {
  font-size: 5em;
}

As of Sass 3.4, you can write this to work both inside a selector and at the root of the document:

@mixin optional-at-root-nest($sel) {
    @at-root #{if(not &, $sel, selector-nest($sel, &))} {
        @content;
    }
}

@mixin context($size) {
    @include optional-at-root-nest('body.#{$size}') {
        @content
    }
}

div {
    span {
        font-size: 2em;
        @include context('large') {
                font-size: 5em;
        }
    }
}

@include context('large') {
    font-size: 2em;
}


来源:https://stackoverflow.com/questions/19031079/sass-content-block-mixin-or-placeholder-that-takes-contextual-selectors-and-a

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