1

I want to use media queries to slightly modify my CSS for different devices. Ideally, I'd like to create a baseline version of a class or rule, and then override it only partially, like this:

.myClass {
    font-family:Helvetica;
    color:#333333;
    font-size:20px;
}

@media screen and (min-width: 1000px) {
    .myClass {
        font-size:30px;
    }
}

My question is, for screens that match the media query, will .myClass completely replace the baseline one (thereby wiping out the font and color property-value pairs), or will it retain those and only override the font-size value?

It seems to work, but I want to know if this is expected behavior. Thank you!

Brian Rak
  • 4,912
  • 6
  • 34
  • 44

1 Answers1

2

It will retain those and only override the font-size value. In other words, when the media query is fulfilled, it behaves the same as:

.myClass {
    font-family:Helvetica;
    color:#333333;
    font-size:20px;
}

.myClass {
    font-size:30px;
}

And when it doesn't, the second rule disappears leaving just the first.

This is expected behavior; @media rules do not affect the cascade in any way other than to apply the enclosed rules only under specific conditions.

If you need to apply only either one rule or the other (i.e. the rules need to be mutually exclusive), you have two options:

  1. Reset the font-family and color declarations in your second rule:

    .myClass {
        font-family:Helvetica;
        color:#333333;
        font-size:20px;
    }
    
    @media screen and (min-width: 1000px) {
        .myClass {
            font-family:inherit;
            color:inherit;
            font-size:30px;
        }
    }
    
  2. Enclose the first rule in a negated version of your media query:

    @media not screen and (min-width: 1000px) {
        .myClass {
            font-family:Helvetica;
            color:#333333;
            font-size:20px;
        }
    }
    
    @media screen and (min-width: 1000px) {
        .myClass {
            font-size:30px;
        }
    }
    

See my answer to these similar questions for a much more detailed write-up:

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Awesome! I guess I never realized that a second declaration of a rule set would retain properties of the first that it did not override. Thank you for your fast and thorough answer! – Brian Rak Mar 27 '14 at 00:40