Default CSS overriding media query

2019-01-27 12:15发布

问题:

I'm getting this from Chrome ADB plugin, connecting to my phone via USB. Basically allowing me to inspect elements on my android chrome and view or alter them on my connected PC.

I am getting this strange issue. I thought media queries were to overrule generic class rules, but if you see this image you can see that the media query rules are being overridden. I COULD fix this by adding !important but I would rather not, I also realize that the rule for non-media-queried container h1 is declared AFTER the media query rule. I am not sure if that is why, or if there is another reason. Can anyone explain why this is happening?

CSS code:

@media screen and (max-device-width: 767px) {
  .container > h1 {
    font-size: 40px;
    line-height: 40px; }
    ...some more rules... }
.container > h1 {
    margin: 0;
    font-size: 80px;
    font-weight: 300;
    line-height: 80px; }

EDIT - Added Example

See this: http://jsfiddle.net/djuKS/ Notice if you swap the rule order, the behaviour is as expected. But by default the media query is being overridden

回答1:

I thought media queries were to overrule generic class rules,

Rules inside a MQ are rules like any other one in terms of priority of their selector, except they will only apply depending on the conditions of the at-media.

(...) I also realize that the rule for non-media-queried container h1 is declared AFTER the media query rule.

You found the correct reason: both rules have exactly the same priority (specificity) as they have the exact same selector. If a property is part of both rules (and the declaration is valid and both of them or none of them has !important modifier), then the value of the last declaration written will apply.
That's the reason you'll always find MQ written at the end (except rules applying to IE8- via conditional classes, no possible overlap between MQ and modern browsers and IE8- :) )