Site sections

List inheritance and Descendant Selectors

Russ Weakley
23-Sep-03

This is a simple step-by-step demonstration to show how inheritance affects nested list items.

If we start applying CSS rules to a multi-nested list, the main thing to remember is than many CSS rules - particularly font sizes - will be interited by elements further down the document tree.

Step 1

If you set a rule for one level of UL only, it will be inherited by all nested lists below. The rule UL { color: red; } will affect the top level list, and all levels of nested list below it, making them all red.

In this example, the relative font size of 85% is inherited, making the nested lists smaller at each level of the document tree. A second level list will become 85% x 85% = 72.25%. A third level list will become 85% x 85% x 85% = 61.4%.

Step 2

If you want to target nested items, the best method is to use Descendant Selectors, as they select items that are descendants of an element.

One example of a Descendant Selector is ul ul { color: blue; }. This rule will affect any second level UL, but will also be inherited by all other lists below. As you can see here, all nested lists below become blue.

To get around the relative font size inheritance problem, you can add to the rule above with ul ul { font-size: 100%; color: blue; }. This will be inherited by all nested lists below - bringing them back up to the correct size. The first UL is scaled to 85%. The second UL would be scaled to 85% x 85%, but instead is set to 100%, making 85% x 100% = 85%. As you can see, this will be inherited by all lower levels.

Step 3

The new rule of ul ul ul { color: green; } will affect all third-level nested lists and be inherited by any nested lists below.

Step 4

The new rule of ul ul ul ul { color: brown; font-weight: bold; } will affect all fourth-level nested lists and be inherited by any nested lists below.

Step 5

You can also isolate a level of nesting by simply targeting that level. In this case, ul { color: red; } is inherited by all nested lists below, and a ul ul ul ul { color: blue; } affects only fourth level lists. Any list below this will also follow the blue style.

Step 6

In this case, the same result can be achieved with li li li li { color: blue; }.

Step 7

You may wish to use LI if you want to target the actual list items but not the overall list. In this case li li li li { color: blue; padding: .5em 0; } is used to add padding to the top and bottom of fourth level list items, but not to the overall list. The same effect could also be achieved with ul ul ul ul li { color: blue; padding: .5em 0; }.