HTML:
<ul id="menu">
<li><a href="" class="active">Portfolio</a></li>
<li><a href="">Services</a></li>
<li><a href="">About</a></li>
<li><a href="">Testimonials</a></li>
<li><a href="">Request a Quote</a></li>
</ul>
CSS:
ul#menu li {
display:inline;
margin-left:12px;
}
Is there a difference between using “ul#menu li” and just “#menu li“? I used both versions and they seem to accomplish the same thing. Is there a reason why most tutorials use add the “ul” before the id?
There is one obvious difference and one more subtle difference.
The obvious difference is that
#menutargets all elements with the ID#menu, whereasul#menuonly targetsulelements. If you only give the ID#menutoulelements, the selectors will always have the same result.There is one potential difference with something called specificity. This is a way of determining which rule to use in case of conflicts. So if you have these two rules:
the second rule will win, because it is more specific, and the text will be red. The rules for specificity are complex and not always intuitive, but in this case the simple result is that
ul#menu liis slightly more specific than#menu li. If you only have one stylesheet, this is unlikely to be an issue for you. If you have several stylesheets, it can be confusing to work out why a certain rule is being ignored; specificity is often the answer.As to why most tutorials use
ul#menu, I don’t know. (In fact, I only have your assertion as evidence that they do!) My guess is that they are making things Really Very Obvious for the sake of idiot readers.