So, this may sound idiotic but, I have been doing the CSS for the navbar's unordered list items as (.nav ul li a). But about a few days ago, I was trying something to see if there is any changes. I just used (a) and changed its border to none and border-bottom to solid 1px cyan and it works. Is there any difference between (.nav ul li a) & (a) while doing the CSS?
CodePudding user response:
there is a huge difference.
css selector engine would use and apply rules only on acnhor tag within a hirarchy of selector query i.e. NAV UL LI A. simply put apply rules on anchor tag within li tag that is within ul tag that is within nav tag. does not touch anything else
nav ul li a {
color: red;
}
<a href='#'>outside of nav</a>
<nav>
<ul>
<li><a href='#'>inside of nav</a></li>
<li><a href='#'>inside of nav</a></li>
</ul>
</nav>
<a href='#'>outside of nav</a>
another perspective for example sake
nav ul li a {
color: red;
}
<a href='#'>outside of nav</a>
<nav>
<ul>
<li><a href='#'>inside of nav ul li</a></li>
<li><a href='#'>inside of nav ul li</a></li>
<a href='#'>outside of li tag becuase it doesnot match 'nav ul li a' rule becuase selector goes on to dig deep into li tag since anchor tag is outside it discards it all together </a>
</ul>
</nav>
<a href='#'>outside of nav</a>
But we only use A as selector query it does not care where the A is it just applies it on every single acnhor tag it can find in whole of document. same would have been the case with 'nav ul a' it would not care wether a is within li or outside it would apply it on every single a tag found with in nav ul tag. same is the case with 'nav a' any and every anchoir tag with in nav tag. Thus in fact 'a' simply means each and every anchor tag within whole of doucment.
a {
color: red;
}
<a href='#'>outside of nav</a>
<nav>
<ul>
<li><a href='#'>inside of nav</a></li>
<li><a href='#'>inside of nav</a></li>
</ul>
</nav>
<a href='#'>outside of nav</a>
I would further advise have breif read about how css selector engine works.
CodePudding user response:
If you add css propery for nav ul li a
the css propery will only apply to the anchor tag within the navbar. If you have any anchor tag outside the navbar the css property will not apply to it. If you just give css for anchor tag the property will apply for all the anchor tags present in the html.
nav ul li a {
color: red;
}
<a href='#'>outside of nav</a>
<nav>
<ul>
<li><a href='#'>inside of nav ul li</a></li>
<li><a href='#'>inside of nav ul li</a></li>
<a href='#'>outside of li tag becuase it doesnot match 'nav ul li a' rule becuase selector goes on to dig deep into li tag since anchor tag is outside it discards it all together </a>
</ul>
</nav>
<a href='#'>outside of nav</a>