Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

:last-child — the last element among siblings

The :last-child pseudo-class selects an element that is last among its element siblings. It tests tree position, not visual order.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

:last-child

:last-child is an argument-free pseudo-class equivalent to :nth-last-child(1). It matches an element last among its element siblings; text and comments do not affect this position. An only child also matches.

li:last-child requires the li to be the last element, not merely the last li. A later element of another type prevents a match; li:last-of-type instead tests position among elements of the same type.

In #items > li:last-child, > restricts selection to direct children. Appending Gamma moves the match from Beta to Gamma. The document tree matters, not visual layout.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>:last-child</title>
<style>
  #items > li:last-child { font-weight: bold; }
</style>
<ul id="items">
  <li>Alpha</li>
  <li>Beta</li>
  <!-- Trailing comment -->
</ul>
<pre id="result"></pre>
<script>
  const items = document.getElementById('items');
  const result = document.getElementById('result');
  const selector = '#items > li:last-child';
  const before = document.querySelector(selector)?.textContent ?? 'none';
  const tail = document.createElement('li');
  tail.textContent = 'Gamma';
  items.append(tail);
  const after = document.querySelector(selector)?.textContent ?? 'none';
  result.textContent = `before: ${before}\nafter: ${after}`;
</script>
</html>

Result

before: Beta
after: Gamma

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources