So for instance, if I had a media query and also some regular CSS with the !important rule on stuff, would it be affected?
For example:
a{
color:#0000FF!important;
}
@media (max-width: 300px){
a{
color:#FF0000;
}
}
Media queries and @media
rules do not affect the behavior of !important
in any way, because they do not have any effect on any part of the cascade. (By extension, this also means you cannot use a @media
at-rule to "remove" an !important
flag, even if you use a more specific selector.)
When your media query is matched, the browser sees this:
a{
color:#0000FF!important;
}
a{
color:#FF0000;
}
And when it doesn't, it sees this:
a{
color:#0000FF!important;
}
Both cases result in the first ruleset taking precedence, but do not prevent, for example, an !important
declaration with a more specific selector, or an !important
inline style, from overriding it.
Here's another example which illustrates this better:
a{
color:#0000FF!important;
}
@media (max-width: 300px){
a:link,a:visited{
color:#FF0000!important;
}
}
When the media query is matched, the browser sees this:
a{
color:#0000FF!important;
}
a:link,a:visited{
color:#FF0000!important;
}
This results in the second rule taking precedence because it has a more specific selector (at least for a
elements that match either pseudo-class). If it didn't match the media query then only the first rule would have any effect, as above.
Yes. Typically if you need to use !important
, something can be improved in your code. Here, you can see that it is overriding the media queries' change: JS Fiddle
If you remove !important
form the code, the media query works as designed: JS Fiddle working properly
Recommended reading on when to use !important
:
When Using !important is The Right Choice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With