A selector that never shipped

CSS has been asked for ::nth-letter since 2003, and the requests keep coming. The case is easy to make: ::first-letter has long existed to mimic print effects such as drop caps, so a sibling selector for the nth character looks like an obvious extension. In 2026 it still isn't possible to write the kind of selector Chris Coyier imagined back in 2011.

h1.fancy::nth-letter(n) {
  display: inline-block;
  padding: 20px 10px;
  color: white;
}

h1.fancy::nth-letter(even) {
  transform: skewY(15deg);
  background: #C97A7A;
}

h1.fancy::nth-letter(odd) {
  transform: skewY(-15deg);
  background: #8B3F3F;
}

The CSS Parser API, hoped for since 2017, has not materialized either. Even if it did, its purpose would not be to let developers invent new syntax. The 2021 unofficial draft suggests it would expose the browser's parser for programmatic use, not customize how CSS is interpreted. Custom pseudo-elements would belong to a hypothetical CSS Renderer API that nobody has proposed. Bramus from the Chrome team has a draft for a CSS parser extensions API, but it doesn't cover custom pseudo-elements. The HTML-in-canvas API proposal, already experimentally available in Chrome, lets elements be rendered differently without DOM changes, but still offers no arbitrary pseudo-element styling.

What the demos show

An interactive CodePen runs the invalid ::nth-letter syntax, and a video demo shows the syntax being used by an eight-year-old. With the feature, the text vortex scrolling effect could drop its JavaScript and rely on ::nth-letter plus the sibling-index() function, which restricts it to Chrome and Safari. Temani Afif's direction-aware elastic hover could lose the spans wrapped around each letter in the original markup. Every typography styling demo could be upgraded in the same way.

Shim, not polyfill

Philip Walton at Google tried hard to make production-ready CSS polyfills and concluded that a reliable one is not possible. The framework he created for building them is abandoned, still works, and is old enough that its examples polyfill flexbox. Perfect CSS polyfills don't appear to have become more feasible in the decade since.

Useful imperfect ones do exist, such as the scroll-timeline polyfill and the container-query polyfill from GoogleChromeLabs. Anything built for ::nth-letter is technically a shim rather than a polyfill, since it patches CSS to add functionality that never existed and has no spec. The closest thing to a draft was Adobe's experimental WebKit work in 2012, which went nowhere. With no spec to follow, the implementation behaves according to the author's own choices.

Deciding what the terms mean

Jeremy Keith raised questions about how such a selector would even behave. Consider markup where the third character is ambiguous:

<p>AB<span>CD</span>EF</p>

The third letter could be "C", the third character read left to right, in the same way p::first-letter selects "A" even when it is nested deep in markup. It could be "E", since E is the third direct child of the paragraph and that is what :nth-child would pick. Or it could be "D" or "B" under a right-to-left writing direction, or with Hebrew characters, which are inherently right-to-left in Unicode.

This implementation treats ::nth-letter as matching direct children in source order, the same rule as :nth-child. On the second question, "letter" is aliased to "character". Half the web doesn't use English, writing directions vary, and some languages represent one letter with multiple characters. ::first-letter should select all parts of such a letter in theory, but browser support for that is poor, and it has other oddities, like selecting punctuation along with the first letter. Rather than disappoint anyone whose idea of a letter differs, the shim keeps punctuation colorable, which an eight-year-old's rainbow text requires.

How the shim works

The shim is published on npm as ::nth-letter and pulled in through unpkg; the package got 1.3k downloads in its first week. Rather than attempting perfection, it does the simplest thing that works: rewrite the CSS, transform the DOM, and let the browser handle the rest. The simplified version is 29 lines of JavaScript.

import getCssData from 'get-css-data';
import { SplitText } from 'gsap/SplitText';

getCssData({
  onComplete(cssText, cssArray, nodeArray) {
    nodeArray.forEach(e => e.remove());
    const selectors = new Set();
    const nthArgs = new Set();
    cssText = cssText.replace(/\/\*[\s\S]*?\*\//g, '');
    // Replace ::nth-letter with :nth-child in CSS
    let rewrittenCss = cssText.replace(
      /([^,{{\r\n]+?)::?nth-letter[ \t]*\(([^\n)]*)\)/gi,
      (full, selector, args) => {
        selector = selector.trim();
        selectors.add(selector);
        nthArgs.add(args);
        // Use :nth-child instead of ::nth-letter
        return `${selector} .char:nth-child(${args})`;
      }
    );
    document.head.insertAdjacentHTML("beforeend", `<style>${rewrittenCss}</style>`);
    selectors.forEach(selector => {
      document.querySelectorAll(selector).forEach(el => {
        if (el.hasAttribute('data-nth-letter')) return;
        el.setAttribute('data-nth-letter', 'attached');
        new SplitText(el, { type: 'chars', charsClass: 'char' });
      });
    });
  }
});

Intercepting CSS that the parser discards

Patching CSS offers no equivalent of monkey patching in JavaScript, and carries comparable risks. Making the nonstandard syntax even visible to script is tricky, because the CSS parser discards invalid CSS, so .rainbow::nth-letter(2n) never reaches the styleSheets property.

The get-css-data package collects raw CSS without judging its validity, concatenating the contents of style tags and using fetch for each stylesheet linked via link tags. A CORS policy that disallows those fetches breaks this, an inherent limit of CSS polyfills. The nonstandard CSS is then rewritten with regular expressions, a looser approach than running PostCSS at build time, but sufficient because the task is a find-and-replace rather than real parsing.

Invalid CSS such as:

.rainbow::nth-letter(n) {
  color: #f432a0;
}

becomes valid CSS:

.rainbow .char:nth-child(n) {
  color: #f432a0;
}

This follows the least-bad strategy identified in a video on CSS polyfills: "rewrite the CSS to target individual elements while maintaining cascade order." Walton adds that he has "never seen a polyfill do this. I don't recommend it, but I think it's the best of the bad options."

getCssData({
  onComplete(cssText, cssArray, nodeArray) {
    nodeArray.forEach(e => e.remove());
    const selectors = new Set();
    const nthArgs = new Set();
    cssText = cssText.replace(/\/\*[\s\S]*?\*\//g, '');
    // Replace ::nth-letter with :nth-child in CSS
    let rewrittenCss = cssText.replace(
      /([^,{{\r\n]+?)::?nth-letter[ \t]*\(([^\n)]*)\)/gi,
      (full, selector, args) => {
        selector = selector.trim();
        selectors.add(selector);
        nthArgs.add(args);
        // Use :nth-child instead of ::nth-letter
        return `${selector} .char:nth-child(${args})`;
      }
    );

    document.head.insertAdjacentHTML("beforeend", `<style>${rewrittenCss}</style>`);
  }
});

Splitting the DOM

Translated CSS still needs elements to style. Collecting the elements that need per-character styling, the shim splits their content into div tags with the free SplitText plugin from GSAP.

selectors.forEach(selector => {
  document.querySelectorAll(selector).forEach(el => {
    if (el.hasAttribute('data-nth-letter')) return;
    el.setAttribute('data-nth-letter', 'attached');
    new SplitText(el, { type: 'chars', charsClass: 'char' });
  });
}

Why not the shadow DOM

Splitting text into one element per character does damage the markup, and a 2021 CSS-Tricks newsletter that lamented ::nth-letter being "sadly still not a thing" called that solution "pretty gross." Splitting also raises accessibility concerns: some screen readers read each character with pauses between. VoiceOver is reported to do this, though the role attribute can now alleviate it. SplitText accounts for screen-reader accessibility automatically, but the approach may still not work on all screen readers.

Hiding the character elements in shadow DOM would come closer to a pseudo-element: presentational markup kept out of the light DOM, with an API for styling from outside. The ::part pseudo-element is the closest tool. Structural pseudo-classes based on tree information, such as :empty and :last-child, cannot be appended to ::part, because a component's consumers shouldn't be able to infer its shadow structure through CSS. The old ::shadow pseudo-element allowed styling :nth-child from outside, but it was deprecated long ago.

A lateral move is to name each character's ::part after the :nth-child selectors already extracted during the regex replacement.

.container::part(character):nth-child(2) {
  color: red;
}

The shadow DOM of such an element would look like this:

<div part="character">1</div>
<div part="character">2</div>

Pre-calculating those selectors as shadow part names, like so, lets them be targeted from outside without touching the light DOM. The shim then generates the shadow DOM with a slightly more complex version of the JavaScript.

.rainbow::part(nth-child\(n\)) {
  color: #f432a0;
}

The markup itself would look something like this:

<h1 class="rainbow">Rainbow</h1>
Rainbow
#ShadowRoot
<span aria-hidden="true" aria-label="Rainbow">
  <div class="char" aria-hidden="true" part="nth-child(n) nth-child(odd)">R</div>
  <!-- etc. -->
</span>
import getCssData from 'get-css-data';
import { SplitText } from 'gsap/SplitText';
getCssData({
  onComplete(cssText, cssArray, nodeArray) {
    nodeArray.forEach(e => e.remove());
    const selectors = new Set();
    const nthArgs = new Set();

    // Remove CSS comments
    cssText = cssText.replace(/\/\*[\s\S]*?\*\//g, '');

    let rewrittenCss = cssText.replace(
      /([^,{\r\n]+?)::?nth-letter[ \t]*\(([^\n)]*)\)/gi,
      (full, selector, args) => {
        selector = selector.trim();
        selectors.add(selector);
        nthArgs.add(args);
        return `${selector}::part(nth-child\\(${CSS.escape(args)}\\))`;
      }
    );

    document.head.insertAdjacentHTML("beforeend", `<style>${rewrittenCss}</style>`);

    selectors.forEach(selector => {
      document.querySelectorAll(selector).forEach(el => {
        if (el.shadowRoot || el.hasAttribute('data-nth-letter')) return;

        const shadow = el.attachShadow({ mode: "closed" });
        el.setAttribute('data-nth-letter', 'attached');
        const wrapper = document.createElement("span");
        wrapper.setAttribute('aria-hidden', 'true');
        wrapper.innerHTML = el.innerHTML;
        shadow.appendChild(wrapper);
        const split = new SplitText(wrapper, { type: "chars", charsClass: "char" });

        nthArgs.forEach((arg, i) => {
          let chars = wrapper.querySelectorAll(`.char:nth-child(${arg})`);
          chars.forEach(c => {
            const prev = c.part || "";
            c.part = (prev ? prev + " " : "") + `nth-child(${arg})`;
          });
        });
      });
    });
  }
});

Two problems make the light DOM the better choice. The shadow variant won't work on elements that don't support attaching a shadow DOM, such as <a> or <p>. And sibling-index() can't be used in styles for a shadow part, since it relies on DOM structure just as :nth-child does, which rules out the text styling demos. ::first-letter is also severely limited in the properties it allows, but that is no reason to knowingly cripple this implementation. The dirty markup is written and maintained by the shim rather than the page author, and if browsers ever ship ::nth-letter natively, the CSS can stay as-is and the library reference simply deleted.

Limits and outlook

With this basis, ::nth-word, ::nth-last-letter and similar selectors become feasible; Coyier covered use cases in his call for ::nth everything. But the shim has real limitations:

  1. It doesn't respond to DOM or style changes made on the fly, though a MutationObserver could support that.
  2. It doesn't work when ::nth-letter appears in a selector passed to querySelectorAll, though monkey-patching JavaScript could fix that.
  3. Its scalability is unknown.
  4. Rewriting all CSS and adding unexpected "char" divs can produce hard-to-diagnose bugs; Philip Schatz's polyfill for the CSS Generated Content Module draft instead makes consumers opt in through special attributes on link or style tags, a compromise that limits the blast radius but is less convenient.
  5. External stylesheets that CORS doesn't allow won't work.

Built into browsers, these selectors would likely be used constantly. Having explored what generic support costs for a result that a few lines of JavaScript often achieves, it's easier to see why browsers hesitate to implement and maintain the feature. The shim might even give them another reason to call native support unnecessary. If it ends up widely used, it might have the opposite effect.