17

i need run the same style with media query and class. For example i need set 200px when screen is less then 500px or when have class .active. How do this in smart way? Without copy/paste code?

Not working:

@media(max-width: 500px), .active {
      width: 200px;
    }
lolalola
  • 3,689
  • 19
  • 57
  • 92

5 Answers5

16

In css, the , is used for grouping, when the same rule applies for several selectors.

However, media queries are not selectors. They consist of a media type and zero or more expressions to check the condition of particular media features. Thus, the , will not work in this case.

If you want to keep it dry, you can give their mixin feature a try.

E.g

@mixin smallWidth() {
    width: 200px;
}

.elem {
    &.active {
        @include smallWidth;
    }

    @media only screen and (max-width : 500px) {
        @include smallWidth;
    }
}
choz
  • 16,299
  • 3
  • 46
  • 69
14

Mixins are a simple solution, but they duplicate the CSS in the final output. A better solution may be to inverse the logic entirely.

In boolean algebra, de Morgan's theorem states that A || B is the same as !(A && B). In your case, this means thinking about your problem in a mobile-first way:

.elem {
  width: 200px;

  @media (min-width: 501px) {
    &:not(.active) {
      width: auto; // or whatever
    }
  }
}
Axel
  • 857
  • 1
  • 8
  • 23
3

CSS provides no means to say "When a media query OR a given class applies".

With plain CSS you can only:

.active {
    width: 200px;
}

@media(max-width: 500px) {
      * {
          width: 200px;
      }
}

with SASS you can use a mixin, but it isn't really efficient for a single rule like that:

@mixin my-width {
    width: 200px;
}

.active {
    @include my-width;
}

@media(max-width: 500px) {
      * {
          @include my-width;
      }
}
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
-3

Try this one.

@media only screen and (max-width: 500px) {
    .active {
          width: 200px;
        }
    }
Undecided Dev
  • 790
  • 4
  • 15
-3

you have to declare the media and your class separated:

@media(max-width: 500px) { .active {
        width: 200px;
    }
}
gerardet46
  • 78
  • 9