Why media queries has less priority than no media queries css

后端 未结 2 2121
情话喂你
情话喂你 2020-11-28 15:01

I want to know why the media queries has less priority than normal css? How to work around to make the media queries more important?

相关标签:
2条回答
  • 2020-11-28 15:42

    This has to do with the way the Cascade in CSS works. When two conflicting rules target the same element, the browser uses the rules of the cascade to determine which one to apply.

    Selector specificity is the most important part of this: styles with a more specific selector will override those with a less-specific selector... but media queries do not change the specificity of your selectors. This means that your two selectors have the same specificity. When that happens, the one appearing later in your stylesheet will override the earlier one.

    Your easiest and best fix is to swap the order of your rulesets:

    .logo img{
        width: 100%;
    }
    
    @media screen and (min-width: 100px) and (max-width: 1499px) {
      .logo img {
         width: 120%;
      }
    }
    

    This way, the media query comes later, and will override the earlier rule when the media query matches the viewport size.


    If that's not an option for some reason, you will need to increase the selector specificity of the rule you want to win. Changing it to the following would work:

    @media screen and (min-width: 100px) and (max-width: 1499px) {
      .logo img {
         width: 120%;
      }
    
    }
    .logo a img{
        width: 100%;
    }
    

    This way the selector now has two tags and a class, or [0,1,2], making it more specific than one tag and one class, or [0,1,1] (the zero in each of those indicates no ids, which are highly specific).


    Do not use !important to fix specificity issues like this. If you need to override the style again elsewhere, the only way to do it is to add another !important. This will eventually lead to !importants all over the place, and then you will still need to deal with the specificity of the selectors.

    0 讨论(0)
  • 2020-11-28 15:52

    While linking the css files in head section, just include the file with the media queries at the last. This way, it can override other style rules, if they have same specificity. This worked well for me.

    0 讨论(0)
提交回复
热议问题