Search code examples
csssassbreakpoints

SCSS how can I group and reuse a block of classes and styles?


I have a component that uses media queries to add new styles on the medium-up breakpoint.

The SCSS looks something like this:

.mycomponent {
  // Bunch of mobile-first styles and classes
    
    @include media-breakpoint-up(md) {
      // Bunch of styles and classes for medium and up.
    }
}

However, I now want to add a modifier that essentially adds the medium-and-up styles on large-and-up instead.

I can do this as such, using the :not selector:

.mycomponent {
  // Bunch of mobile-first styles and classes
}

.mycomponent:not(.mycomponent--lg) {
    @include media-breakpoint-up(md) {
      // Bunch of styles and classes that appear on med-up
    }
}

.mycomponent--lg {
    @include media-breakpoint-up(lg) {
      // Bunch of styles and classes identical to above but now appearing on lg-up
    }
}

HTML would look like:

<div class="mycomponent">Shows different styling on medium and up</div>
<div class="mycomponent mycomponent--lg">Shows different styling on large and up</div>

The above SCSS works, but I've got a lot of duplication. The styles and classes between each breakpoint are identical.

Apart from placing the styles on their own file and using @import, is there any way to group them on the same page and just pull them into each breakpoint when I need them?


Solution

  • SCSS's %placeholder would have been a good idea, but they don't seem to work when placed in media queries.

    Instead I had to make a mixin:

    .mycomponent {
      // Bunch of mobile-first styles and classes
    }
    
    @mixin desktopStyles {
      // Bunch of styles and classes for larger break points
    }
    
    .mycomponent:not(.mycomponent--lg) {
        @include media-breakpoint-up(md) {
            @include desktopStyles;
        }
    }
    
    .mycomponent--lg {
        @include media-breakpoint-up(lg) {
            @include desktopStyles;
        }
    }