htmlcsscss-selectorscss-specificity

Am I messing with specificity ? What's going on?


I will short and clear. I have this html code snippet.

  <nav>
 <span class="heading"><a href="#">CodingHero</a></span>
        <ul>
            <li><a href="#Home" class="active">Home</a></li>
            <li><a href="#About">About</a></li>
            <li><a href="#Services">Services</a></li>
            <li><a href="#Contact">Contact</a></li>
         </ul>
   </nav>

Now I have this CSS part

nav ul li a {
        font-family:'Poppins', sans-serif;
        font-size:20px;
        color:white;
        opacity:0.8;
        margin:0px 20px;
    }

This is also okay. But I found this weird behavior while dealing inside media queries.

nav ul a {
            font-size:44px;
            background-color:yellow;
            margin:0px;
        }

My background color works yellow fine. But my font-size and margin doesn't work. As soon as I provide specificity as I originally used in CSS part,

nav ul li a {
            font-size:44px;
            background-color:yellow;
            margin:0px;
        }

This works, my font-size and margin also comes into effect. Can someone explain why I have to use the original selector that I first used to get all properties to act? Why my font-size and margin were not applied when background color in same part is applied. What's going on here? Any resources to clear my head. Any response is appreciated. Thanks !


Solution

  • background-color:yellow; was applied because the other selector with higher specificity (nav ul li a) doesn't contain a background-color property, so nothing overrides it.


    If you were to add one like

    nav ul li a {
        font-family:'Poppins', sans-serif;
        font-size:20px;
        color:white;
        opacity:0.8;
        margin:0px 20px;
        background-color: red; /* added */
    }
    

    then it'll override background-color:yellow, just like it override margin and font-size