Search code examples
htmlcssmedia-queries

Why is my media query rule not being prioritized?


I'm using media queries to make my site resposnive. In my CSS doc, the media queries are below all other styles. I'm am using diplay: none; which works perfectly but on another div the original width is taking priority even when I reduce the browser size.

Image of dev console:

Image of dev console

Do I really have to add !important to every media rule?

CSS:

@media screen and (max-width: 930px) {

    /* INDEX */
nav ul {
    display: none;
}

#sliderContainer {
    width: 80%;
    height: auto;
}


}

Solution

  • The rule at line #112 in index.css is also applied by #sliderContainer and not by nav li, as you state in your question (it can be seen in the image you posted). Because it is met later and has same specificity, it applies.

    If you place !important on a rule, you'll probably need to use !important when trying to override it, and before you know it, half your rules will be !important and fixing responsiveness is going to be a nightmare. Either slightly increase specificity of your rule or change their order.

    Very important note: @media queries do not add any specificity to CSS rules. They just make them apply (when conditions are true) or not (when not true).

    Useful note: A very good technique to always keep specificity of your selectors as low as possible is to place your custom stylesheets last inside <head>, after any theme/libraries/plugins stylesheets. Whenever you need to override anything, you just copy-paste the selector from where it is currently defined, and only placing it in your custom stylesheet will make it have priority without higher specificity.