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

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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


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