Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't media queries override normal CSS? [duplicate]

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.

CSS

.loginbar {
    padding: 20px;
}
.logo {
    display: inline-block;
}

@media screen and (max-width: 1042px) {
        .loginbar {
            padding: 10px !important;
        }
        .logo {
            diplay: none !important;
        }
    }

HTML

    <div class=".logo"></div>
    <div class="loginbar"><a href="#">Log In | Sign Up</a></div>
like image 991
grantfoster Avatar asked Apr 11 '17 14:04

grantfoster


1 Answers

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.

like image 74
Richard Parnaby-King Avatar answered Nov 02 '22 23:11

Richard Parnaby-King