Why media queries has less priority than no media queries css

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?

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

}
.logo img{
    width: 100%;
}
<div class="logo">
  <a href="/#!/"><img src="http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg" alt="image"></a>
</div>

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.