An important rule overrides media queries?

So, for example, if I had a media query, as well as some regular CSS with an important rule on the material, would that affect it?

For instance:

a{ color:#0000FF!important; } @media (max-width: 300px){ a{ color:#FF0000; } } 
+6
source share
2 answers

Media queries and @media rules do not affect !important behavior in any way, because they do not have any effect on any part of the cascade , (In addition, this means you cannot use the @media to β€œremove” the !important flag , even if you use a more specific selector.)

When your media query matches, the browser sees this:

 a{ color:#0000FF!important; } a{ color:#FF0000; } 

And when it is not, he sees this:

 a{ color:#0000FF!important; } 

Both cases lead to the fact that the first set of rules takes precedence, but does not prevent, for example, the declaration of !important with a more specific selector or built-in !important style from overriding.

Here is another example that illustrates this better:

 a{ color:#0000FF!important; } @media (max-width: 300px){ a:link,a:visited{ color:#FF0000!important; } } 

When a media request is matched, the browser sees this:

 a{ color:#0000FF!important; } a:link,a:visited{ color:#FF0000!important; } 

This leads to the fact that the second rule takes precedence, since it has a more specific selector (for at least a elements that correspond to the pseudo-class ). If this does not match the media query, then only the first rule will have any effect, as indicated above.

+6
source

Yes. Usually, if you need to use !important , something can be improved in your code. Here you can see that this overrides the change in media queries: JS Fiddle

If you remove the !important code form, the media request will work as designed: JS Fiddle works correctly


Recommended reading on when to use !important :
Using! important - the right choice

+1
source

Source: https://habr.com/ru/post/971816/


All Articles