Emmanuel Akinfulubi

HTML and CSSHTML and CSS

Create a nested list in HTML

8 A nested list, nested correctly

easy

Put a sub-list under one item of a list. The nesting has to be inside the item it belongs to, which is where most people get it wrong.

Stuck? Three hints, smallest first
  1. 1. The inner <ul> goes inside the <li>, before its closing tag.
  2. 2. A list may only contain <li> children, so a <ul> after </li> is invalid.
  3. 3. Change the marker at the second level so the hierarchy reads at a glance.

index.html

<ul class="routes">
  <li>Northbound
    <ul>
      <li>Abuja</li>
      <li>Kano</li>
    </ul>
  </li>
  <li>Eastbound
    <ul>
      <li>Enugu</li>
    </ul>
  </li>
  <li>Local shuttle</li>
</ul>

style.css

.routes {
  margin: 0;
  padding-left: 1.3rem;
  list-style-type: disc;
}

/* Second level: a different marker, so depth is visible without indentation
   alone carrying the message. */
.routes ul {
  margin: 0.3rem 0 0.5rem;
  padding-left: 1.2rem;
  list-style-type: circle;
}

.routes > li {
  margin-bottom: 0.35rem;
  font-weight: 600;
}

.routes ul li {
  font-weight: 400;
  color: #5c5c66;
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
7 checks that prove this answer

Assertions, run in the browser. The markup and styles above are handed to them as html and css, so press Run and each check prints ok. The build fails if a single one fails.

Checks for exercise 8

// A nested list must sit inside an li. The classic error is closing the li
// first, which puts a ul where only li is allowed.
const nestedInsideItem = /<li>[^<]*\s*<ul>/.test(html);
const nestedAfterItem = /<\/li>\s*<ul>/.test(html);

test('the sub-list is inside its item', nestedInsideItem, true);
test('and never a sibling of it', nestedAfterItem, false);
test('two levels of list', countTag(html, 'ul'), 3);
test('six items across both levels', countTag(html, 'li'), 6);
test('the second level uses a different marker', /list-style-type\s*:\s*circle/.test(css), true);
test('the first level keeps the disc', /list-style-type\s*:\s*disc/.test(css), true);
test('the child selector styles only top-level items', /\.routes\s*>\s*li/.test(css), true);

Output


      

<ul> and <ol> may only contain <li>, so a sub-list placed after </li> is invalid and browsers recover from it inconsistently — usually by rendering an extra level of indentation that no element accounts for. The second check is there to catch exactly that. The > in .routes > li is doing real work too: without it, the bold rule would apply to the nested items as well, since they are also descendants.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.