Search code examples
csssassextend

merge @extend with parent style and make one class name


I'm trying to merge the style into one class but its showing an error. Look at the example below.

%banner-style{
  banner {
    padding: 140px 0 210px;
    background: url(https://im2.ezgif.com/tmp/ezgif-2-92c6382d82ba.jpg) top center/cover no-repeat;
    &.row {
        margin: 0;
    }
    .main-heading {
        font-size: 40px;
        letter-spacing: -1px;
        font-weight: 600;
        padding-right: 20px;
        sup {
            font-size: 10px;
            vertical-align: super;
        }
    }
  }
}

And I want it to merge with the parent class .parent

.parent{
  color: red;
  &_@extend %banner-style;
}

using & to merge into one class name. but showing error unless i do this

.parent{
      color: red;
      &_{@extend %banner-style};
    }

Which is same as if I remove &_.

I wanted .parent_banner {...} but instead got .parent_ banner{...};

Does anyone know how I can accomplish this?


Solution

  • You are getting exactly what is supposed to happen. Extend does not "merge" classes, it extends another class/placeholder into a new selector's styles.

    What that means is if I write:

    %banner-style {
      background: black;
    }
    
    .parent { 
      @extend %banner-style;
    }
    .other-selector { 
      @extend %banner-style;
      color: red;
    }
    

    The css I get will be

    .parent {
      background: black;
    }
    .other-selector {
      color: red;
      background: black;
    }
    

    So you are getting expected results. If you'd like to make this "work" the way you want, you can just change your code to:

    %banner-style {
        padding: 140px 0 210px;
        background: url(https://im2.ezgif.com/tmp/ezgif-2-92c6382d82ba.jpg) top center/cover no-repeat;
        &.row {
            margin: 0;
        }
        .main-heading {
            font-size: 40px;
            letter-spacing: -1px;
            font-weight: 600;
            padding-right: 20px;
            sup {
                font-size: 10px;
                vertical-align: super;
            }
        }
    }
    
    .parent{
      color: red;
    
      &_banner {
        @extend %banner-style;
      };
    }
    

    Note: I took out the banner block because it seems you don't want that (and banner isn't a normal html element).