Extending selectors from within media queries with Sass

前端 未结 6 1584
别跟我提以往
别跟我提以往 2020-11-29 00:12

I have an item class and a compact \"modifier\" class:

.item { ... }
.item.compact { /* styles to make .item smaller */ }

This is fine. How

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 00:34

    For the record, here is how I ended up solving the problem with only duplicating generated styles once:

    // This is where the actual compact styles live
    @mixin compact-mixin { /* ... */ }
    
    // Include the compact mixin for items that are always compact
    .item.compact { @include compact-mixin; }
    
    // Here's the tricky part, due to how SASS handles extending
    .item { ... }
    // The following needs to be declared AFTER .item, else it'll
    // be overridden by .item's NORMAL styles.
    @media (max-width: 600px) {
      %compact { @include compact-mixin; }
    
      // Afterwards we can extend and
      // customize different item compact styles
      .item {
        @extend %compact;
        /* Other styles that override %compact */
      }
      // As shown below, we can extend the compact styles as many
      // times as we want without needing to re-extend
      // the compact mixin, thus avoiding generating duplicate css
      .item-alt {
        @extend %compact;
      }
    }
    

提交回复
热议问题