Passing css property:value into a mixins argument

2019-01-19 07:46发布

问题:

Is something like the following dummyexample possible in sass/scss? I need something like this to prevent the endless mediaquery repeats for different devices.

// The dummy mixin
@mixin iphone_rules($webapp_portrait:null){


  @if($webapp_portrait != null){
    // Portrait (webapp)
    @media screen and (max-height: 460px){

     // The following line is just a dummy 
     eg. echo $webapp_portrait;
    }
  }
}

// How I want to use it
.mySelector{

   margin-left:10px;
   padding:0px;

   @include iphone_rules('margin-left:20px; padding:2px;');
}

回答1:

Sass does not allow the use of arbitrary strings in place of the property/value syntax.

For most mixins, the @content directive is your best bet for passing in styling information:

@mixin iphone_rules {
    @media screen and (max-height: 460px){
        @content;
    }
}

.mySelector {
    @include iphone_rules {
        margin-left:10px;
        padding:0px;
    }
}

Otherwise, styling information can be passed in as a mapping (or list of lists for Sass 3.2 and older):

@mixin iphone_rules($styles: ()) {
    @media screen and (max-height: 460px){
        @each $p, $v in $styles {
            #{$p}: $v;
        }
    }
}

.mySelector {
    margin-left:10px;
    padding:0px;

    @include iphone_rules(('margin-left': 20px, 'padding': 2px));
}


标签: css sass