Do I need to add !important
to all properties in the media queries I've written for my site like in the example below?
I had the CSS below at the bottom of my stylesheet, but I found that these properties did not reflect my design until I added the !important
tags. I understand that using the !important
tag is not best practice.
.loginbar {
padding: 20px;
}
.logo {
display: inline-block;
}
@media screen and (max-width: 1042px) {
.loginbar {
padding: 10px !important;
}
.logo {
diplay: none !important;
}
}
<div class=".logo"></div>
<div class="loginbar"><a href="#">Log In | Sign Up</a></div>
In theory, no - you don't need the !important
flag. The issue you are probably experiencing arrises from specificity
:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors
Mozzila
The basic math (hugely simplified) behind specificity is a weighted approach.
id
is worth 100,
class
is worth 10,
tag
is worth 1.
Therefore a.class
(tag + class = 11) is less specific that a#id
(tag + id = 101).
CSS is also applied in a last-match-wins format, that is to say that the style for the last declared selector that matches will be applied (sorted according to the above specificity).
So - in your example, it could be that there are elements on you page with the class .element
which is being targeted with a more specific selector (such as .container div > ul li + li .element
(which is a lot more specific than just .element
) so the styles from that is overriding the styles from your media style.
The caveat to this, is if the !important
flag is being used. In which case the only way to override the styles is to supply the !important
flag again.
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