Descendant and child selectors
Most css coders are familiar with the basic descendant selector,
parent child
and use it all the time, perhaps too much.
The descendant selector is applied to every single child of parent and that is not
always ideal.
The direct child selectors
A better solution in some cases is the direct child selector:
parent > child
. The difference between this and the descendant
selector mentioned above is best explained with a nested list
<ul class="menu">
<li> List item 1
<ul>
<li>List item 1.1</li>
<li>List item 1.2</li>
</ul>
</li>
<li>List item 2
<ul>
<li>List item 2.1</li>
<li>List item 2.2</li>
</ul>
</li>
</ul>
If we use the selectors ul.menu li
and
ul.menu > li
the first one will apply only to list items 1 and 2,
while the second will apply to all li elements in the html code above. So they are both useful
and a combination of these two selectors is often needed.
CSS selectors for a dropdown menu
The html code above is conicidentally similar to how I would express a menu in html code. A dropdown menu is a nice case study for exploring basic child/descendant selectors. In a typical dropdown menu, the first level looks like a traditional menu while subsequent levels have a different look. For positioning the second level will be below the first level (in case of a horizontal menu) while the third level and beyond will be positioned to the right of its' parent.
This gives us a laundry list of needed selectors
- For the looks of the first level
- For layout of the first level
- For the looks of the second level and beyond
- For layout of the second level
- For layout of the second level and beyond (some common parts)
- For layout of the third level and beyond
To express these selectors correctly we need html code for our menu:
<ul class="cssv-menu">
<li>
<a href="#">Page 1</a>
<ul>
<li><a href="#">Page 1.1</a></li>
<li><a href="#">Page 1.2</a>
<ul>
<li><a href="#">Page 1.2.1</a></li>
<li><a href="#">Page 1.2.2</a></li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#">Page 2</a>
<ul>
<li><a href="#">Page 2.1</a></li>
<li><a href="#">Page 2.2</a></li>
</ul>
</li>
<li>
<a href="#">Page 3</a>
<ul>
<li><a href="#">Page 3.1</a></li>
<li><a href="#">Page 3.2</a></li>
</ul>
</li>
</ul>
Ok, html code is ready. For simplicity, we will now pretend that all visual styles are applied to the a elements and all layout is controlled by the ul and li elements. With this in mind, our 6 selectors turn out like this:
- For the looks of the first level:
ul.cssv-menu > li > a
- For layout of the first level:
ul.cssv-menu > li
- For the looks of the second level and beyond:
ul.cssv-menu ul a
- For layout of the second level
ul.cssv-menu > li > ul
- For layout of the second level and beyond (some common parts):
ul.cssv-menu > li ul
- For layout of the third level and beyond:
ul.cssv-menu > li > ul > li > ul
By using some basic css on those selectors (and a little extra) we end up with this: