Search code examples
sassmedia-queriesmixins

Styles for multiple breakpoints in SASS


I've defined two mixins in SASS that allow me to place media queries easily. The problem I'm encountering is that I'm repeating myself frequently across many queries. That is to say, some of my style changes are the same for tablet and mobile breakpoints and others are different. Example:

.foo
  float: left
  width: 50%
  +tablet()
    float: none
    display: block
    width: 100%
  +mobile()
    float: none
    display: block
    width: 100%

Where my mixins are defined like this:

=tablet
  @media (min-width: #{$mobile-width} + 1) and (max-width: #{$tablet-width})
    @content

=mobile
  @media (max-width: #{$mobile-width})
    @content

I'd love to do something like this:

...
+tablet(), +mobile
  float: none
  display: block
  width: 100%

That doesn't compile, so what is the best way to keep my SASS stylesheets DRY?


Solution

  • As per @Stefan F's comment, the easiest thing to do in this case was to create a third mixin called (something like): +both() which encapsulated the mobile and tablet sizing. (I'm answering this myself only because he did not and it has been some time.)

    Example:

    =both
      @media (max-width: #{$tablet-width})
        @content
    

    Usage:

    .foo
      float: left
      width: 50%
      +both()
        float: none
        display: block
        width: 100%