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,773
  • 20
  • 60
  • 96

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
  • 17,242
  • 4
  • 53
  • 73
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
  • 867
  • 1
  • 8
  • 24
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
  • 914,110
  • 126
  • 1,211
  • 1,335
-4

Try this one.

@media only screen and (max-width: 500px) {
    .active {
          width: 200px;
        }
    }
Undecided Dev
  • 840
  • 6
  • 16
-4

you have to declare the media and your class separated:

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