ohmygoddess
ohmygoddess

Reputation: 657

CSS multiple descendant selectors

I want to write a horizontal tag list as navigator. I read some css files online, and find the following (desendant?) selector style in a single css file:

  1. nav ul li a { ...}
  2. nav a {...}
  3. nav ul li {...}

I know the for 2, nav a means select all the "a" elements under nav class. But what about 1. and 3.? Does 3. means select all the "li" insinde "ul", and the "ul" should also inside "nav"? It seems to me that 1 and 2. will have similar effect. But I cannot find an answer online.

Upvotes: 2

Views: 3133

Answers (1)

Alec Deitloff
Alec Deitloff

Reputation: 447

The first means that it will apply to all <a> elements inside a <li> which is inside <ul> which is within a <nav>. In other words, it will style code that looks like this:

<nav>
    <ul>
        <li>
            <a>...</a>
        </li>
    </ul>
</nav>

The reason that selector 1 and selector 2 will apply to the same elements is because if you notice <nav><ul><li><a>...</a></li></ul></nav>, the <a> is both times inside the <nav><ul>...</ul></nav>. The first selector is just more restrictive than the second selector, but because everything inside a <ul> is always supposed to also be inside a <li> element, the selectors should always apply to the same elements.

The third selector will apply to <li> elements inside a <ul> which is inside a <nav>, just like you said. In other words:

<nav>
    <ul>
        <li>...</li>
    </ul>
</nav>

Edit: As @Hughes suggested, something to note here is the concept of "specificity." When there are multiple rules that apply to the same object, there is often times a need to break ties. For instance, what happens if we have this code?

nav ul a { color: blue; }
nav ul li a { color: green; }

It's up to CSS to determine which font colour to apply to <nav><ul><li><a> ... </a></li></ul></nav>. In these cases, CSS chooses the rule which is more specific when describing which elements it applies to. In this example, the <a> would be coloured green, because the nav ul li a rule is more specific when describing the elements that the rule should apply to (just think of the English definition for the word "specific"). Thus while both selector 1 and selector 2 from the question should apply to the same objects, if they ever both provide the same CSS property, the value in selector 1 would be chosen over the value in selector 2.

Upvotes: 2

Related Questions