Unexpected results when using @extend for themes

前端 未结 1 1852
抹茶落季
抹茶落季 2020-11-28 16:59

I\'m refactoring some of my Sass code and I came across a weird issue. My code currently looks like this:

// household
$household_Sector: \'household\';
$hou         


        
相关标签:
1条回答
  • 2020-11-28 17:35

    Extends, as you've already discovered, can get rather messy. I would go about solving your problem by using an @content aware mixin in combination with global variables (this uses mappings, which are part of 3.3... you can do it with lists of lists, but it's a little less elegant):

    $base-color: null; // don't touch
    $accent-color: null; // don't touch
    
    $sections:
        ( household:
            ( base-color: #ffc933
            , accent-color: white
            )
        , sports:
            ( base-color: #f7633e
            , accent-color: white
            )
        );
    
    
    // the mixin to output all sector specific css
    @mixin sector-css() {
        @each $sector, $colors in $sections {
            $base-color: map-get($colors, base-color) !global;
            $accent-color: map-get($colors, accent-color) !global;
            &.sector-#{$sector} {
                @content;
            }
        }
    }
    
    .product-paging {
        @include sector-css() {
            h2 {
                background-color: $base-color;
            }
        }
    }
    

    Output:

    .product-paging.sector-household h2 {
      background-color: #ffc933;
    }
    
    .product-paging.sector-sports h2 {
      background-color: #f7633e;
    }
    

    Update: Since you want to guarantee that the sector class is always at the top, you just need to switch around a little.

    @mixin sector-css() {
        @each $sector, $colors in $sections {
            $base-color: map-get($colors, base-color) !global;
            $accent-color: map-get($colors, accent-color) !global;
            .sector-#{$sector} {
                @content;
            }
        }
    }
    
    @include sector-css() {
        &.product-paging {
            h2 {
                background-color: $base-color;
            }
    
            h3 {
                background-color: #CCC;
            }
    
            h2, h3 {
                color: $accent-color;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题