Brian Rak
Brian Rak

Reputation: 5134

Is it okay to partially override a rule via a @media query?

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!

Upvotes: 1

Views: 50

Answers (1)

BoltClock
BoltClock

Reputation: 723568

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:

Upvotes: 2

Related Questions