Style by relationship

Use combinators to reach exactly the right elements, with no new classes.

What to build

Three rules.

Requirements

  • Only the top-level items of the menu have the background lightyellow. The nested items do not.
  • The paragraph immediately after h2 is italic. Other paragraphs are not.
  • Links inside footer are teal. Links elsewhere are not.

Constraints

Do not change the HTML, and do not use classes.

Example

ul > li matches list items directly inside a ul, but not the ones nested more deeply inside ol.

Why it works

Each combinator describes a relationship, so that the rule follows the page's structure.

Hints

Hint 1

Only the top level of the list should change, so use the child combinator.

Hint 2

The summary is the paragraph immediately after the heading.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Site</title>
  <style>
    ul > li { background: lightyellow; }
    h2 + p { font-style: italic; }
    footer a { color: teal; }
  </style>
</head>
<body>
  <ul id="menu">
    <li>Courses
      <ol><li>HTML</li></ol>
    </li>
  </ul>
  <h2>About</h2>
  <p>A short summary.</p>
  <p>More detail.</p>
  <a href="/one">Main link</a>
  <footer><a href="/two">Footer link</a></footer>
</body>
</html>

Lesson: Selectors: choosing what to style →