Search code examples
htmlcsscss-selectorsstylesheet

CSS doesnt overwrite style


I have 2 stylesheet files, style.css, and index.css which are loading respectively

1-style.css 2-index.css

in my style.css I have code like this

#mainNav nav > a:hover span:before {
    background-color: transparent !important;
}

#mainNav nav a.darkBlue span:before {
        background-color: #17729a;
}

now in my index.css

when I write

#mainNav .darkBlue span:before {
background-color: transparent;
}

It doesnt work and I should write !important at the end to make it work

but when I write selectors order in a different way like the way I used in my style.css it works without !important

like this

#mainNav nav a.darkBlue span:before {
    background-color: transparent;
}

Why?


Solution

  • Your declarations are being applied based on how specific they are.

    Per MDN - 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 a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector.

    The link above also goes into the factors that determine specificity:

    The following list of selector types increases by specificity:

    1. Type selectors (e.g., h1) and pseudo-elements (e.g., ::before).

    2. Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).

    3. ID selectors (e.g., #example).

    Universal selector (*), combinators (+, >, ~, ' ') and negation pseudo-class (:not()) have no effect on specificity. (The selectors declared inside :not() do, however.)


    CSS chooses which rules to apply based on a few conditions. Given rules applying to the same element, they are regarded in the following order:

    1. !important

    span { color: red; }               /* base */
    #mySpan { color: blue; }           /* specific  */
    span { color: green !important; }  /* important */
    <span id="mySpan" style="color: purple;">Example</span>

    2. Inline styles

    span { color: red; }               /* base */
    #mySpan { color: blue; }           /* specific  */
    <span id="mySpan" style="color: purple;">Example</span>

    3. Specificity

    span { color: red; }               /* base */
    #mySpan { color: blue; }           /* specific  */
    <span id="mySpan">Example</span>

    4. Last declared

    span { color: red; }               /* base */
    span { color: yellow; }            /* last applied */
    <span>Example</span>


    It's generally best to avoid using !important wherever possible. If you throw them around carelessly, there may come a time when you actually need to override one, but you've already used your highest order of precedence.