lolalola
lolalola

Reputation: 3823

CSS/SCSS media query or class

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;
    }

Upvotes: 19

Views: 15643

Answers (6)

WuLongTi
WuLongTi

Reputation: 23

I know this was asked AGES ago, but a final answer wasn't agreed on and I found a pretty elegant solution when researching this problem so I wanted to share it if anyone else was also looking into this. I don't know if this was available at the time of asking though.

@mixin activeWidth {
  .active{@content}
  @media (max-width: 500px){@content}
}
@include activeWidth {
  width: 200px;
}

Upvotes: 0

Axel
Axel

Reputation: 966

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
    }
  }
}

Upvotes: 15

choz
choz

Reputation: 17898

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;
    }
}

Upvotes: 18

Quentin
Quentin

Reputation: 944294

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;
      }
}

Upvotes: 4

gerardet46
gerardet46

Reputation: 76

you have to declare the media and your class separated:

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

Upvotes: -4

Undecided Dev
Undecided Dev

Reputation: 830

Try this one.

@media only screen and (max-width: 500px) {
    .active {
          width: 200px;
        }
    }

Upvotes: -4

Related Questions