Executive Overview
The evolution of Cascading Style Sheets (CSS) has historically been defined by a strict separation of concerns: static selectors target document structures, while properties dictate visual rendering. For over two decades, developers have relied on hardcoded pseudo-classes like :nth-child() to pattern-match elements based on their structural index. If an architectural requirement demanded that a repetition formula—such as 5n + 8—be updated dynamically at runtime, engineers were forced to rewrite their selectors or resort to JavaScript manipulations.
However, the modern CSS landscape is undergoing a paradigm shift. With the standardization and rollout of advanced style queries, the native inline if() conditional function, and contextual helper functions like sibling-index(), developers are no longer strictly bound by static stylesheets.
This article explores a seemingly counterintuitive technical exercise: re-implementing the native :nth-child() feature set entirely through custom properties and modern inline conditionals. While rebuilding an existing browser-native feature might initially appear redundant, this deep dive unlocks profound architectural insights. By learning how to construct dynamic interval selectors on the fly, front-end engineers gain mastery over emerging CSS features, opening new pathways for highly adaptable, component-driven design systems.
Detailed Chronology & Technical Breakdown
To understand how dynamic structural selection is achieved, we must trace the technical progression from simple exact-match selectors to complex, multi-variable algebraic intervals.
The Core Problem: Static Limitations vs. Dynamic Ambitions
Consider a standard CSS structural rule designed to highlight every fifth element offset by eight:
div:nth-child(5n + 8)
background: red;
If a design system requires the multiplier (5) or the offset (8) to shift in response to user input or state changes, standard CSS offers no direct mechanism. Developers cannot currently interpolate CSS custom properties directly into structural pseudo-class arguments, as seen in this hypothetical—and currently invalid—syntax:
.container
--A: 5;
--B: 8;
/* This is currently invalid CSS */
.container > div:nth-child(var(--A)*n + var(--B))
background: red;
To bypass this limitation, we leverage a clean markup structure—a container holding multiple child elements—and map structural evaluations to style-based conditional logic.

<div class="container">
<div></div>
<div></div>
<div></div>
<!-- ... -->
</div>
By decoupling the layout selector from native pseudo-classes, we pass control variables (--A and --B) directly into the container scope, evaluating element eligibility on individual children via computed properties.
Step 1: Implementing Exact Index Selection (:nth-child(B))
We begin with the simplest possible structural query: targeting a single, exact element index (e.g., div:nth-child(5)).
Instead of relying on the native pseudo-class, we expose the index as a custom property (--B) and evaluate it against the element’s native sibling-index() using the experimental if() function and container style queries:
.container
--B: 5;
.container div
background: if(style(sibling-index() = --B): red; else: lightblue);
color: if(style(sibling-index() = --B): white);
Through this syntax, the if() function evaluates a style query. If the element’s internal sibling index matches the custom property --B, the primary condition executes, applying a red background and white text. Otherwise, a fallback color (lightblue) is rendered.
As explored in foundational style query patterns, conditions inside style() can be written in multiple equivalent, valid ways:
style(sibling-index() = --B)style(sibling-index() = var(--B))style(var(--B) = sibling-index())style(--B = sibling-index())
Step 2: Open-Ended Range Selection (:nth-child(n + B) and :nth-child(-n + B))
Expanding beyond exact matches, developers frequently need to select elements after or before a specific threshold.
To select all elements from a given index onward (:nth-child(n + 5)), we evaluate whether an element’s sibling index is greater than or equal to the threshold:

.container
--B: 5;
.container div
background: if(style(sibling-index() >= --B): red; else: lightblue);
Conversely, selecting all elements up to a maximum threshold (:nth-child(-n + 5)) simply flips the comparative operator:
.container
--B: 5;
.container div
background: if(style(sibling-index() <= --B): red; else: lightblue);
By combining these rules, bounded range selections—traditionally requiring chained pseudo-classes like div:nth-child(n + X):nth-child(-n + Y)—can be streamlined into a single, intuitive expression:
.container
--X: 3;
--Y: 8;
.container div
background: if(style(--X <= sibling-index() <= --Y): red);
Step 3: Periodic Interval Selection (:nth-child(An))
Handling repeating patterns (such as every third element, or 3n) introduces the need for mathematical remainder evaluation. This is achieved using the native mod() function. If the remainder of dividing an element’s index by --A equals zero, it represents a valid multiple:
.container
--A: 3;
.container div
background: if(style(mod(sibling-index(), var(--A)) = 0): red);
While functional for positive integers, edge cases emerge when --A is assigned a negative value. Because mathematical modulo operations can process negative divisors while still returning zero, unintended elements may match. We secure the conditional evaluation by verifying that --A remains strictly positive, chaining conditions with the and keyword:
.container
--A: 3;
.container div
background: if(style((mod(sibling-index(), var(--A)) = 0) and (var(--A) > 0)): red);
Step 4: The General Form (:nth-child(An + B))
Synthesizing multipliers and offsets into a single, comprehensive dynamic equation requires solving for $n$:
$$n = fractextindex – BA$$
For an element to match, two distinct mathematical criteria must be met:

- The quotient must be a positive number or zero: $fractextindex – BA ge 0$
- The division must yield no remainder: $textmod(textindex – B, A) = 0$
Translating this logic into CSS style queries produces a robust, general-purpose selector engine:
.container
--A: 3;
--B: 5;
.container div
background: if(
style(
(mod(sibling-index() - var(--B), var(--A)) = 0)
and (calc((sibling-index() - var(--B))/var(--A)) >= 0)
): red
);
Handling the Division-by-Zero Edge Case
When --A is set to 0, mod() returns NaN, breaking the conditional evaluation. To bulletproof the implementation against zero-values and provide complete parity with native engine behavior, engineers can introduce a local state variable --g powered by the sign() math function:
.container
--A: 3;
--B: 5;
.container div
--n: calc((sibling-index() - var(--B))/var(--A));
--g: if(
style(--A = 0): calc(sign(sibling-index() - var(--B)) + 1);
else: calc(sign(var(--n) + 1) + mod(var(--n), 1))
);
background: if(style(--g = 1): red);
Supporting Context & Metrics
To contextualize the performance and architectural impact of utilizing style queries and inline conditionals for structural matching, consider the following metrics gathered from modern layout testing environments:
| Selector Implementation Strategy | Layout Calculation Overhead | Runtime Flexibility | Browser Baseline Support |
|---|---|---|---|
Native CSS Pseudo-Classes (:nth-child) |
Minimal (Optimized C++ Engine) | Static (Requires DOM/CSS Rewrite) | Universal |
Dynamic Style Queries + if() |
Moderate (Re-evaluates style cascades) | Fully Dynamic (Driven by Custom Properties) | Emerging / Experimental |
| JavaScript-Driven Class Injection | High (Triggers DOM reflows & repaints) | Fully Dynamic (Imperative control) | Universal |
While native selectors remain the gold standard for performance, the ability to shift calculation logic into the CSS cascade reduces reliance on JavaScript layout thrashing. Instead of executing JavaScript MutationObservers to toggle class names when an index interval changes, developers can update a single CSS custom property (--A or --B), delegating visual updates directly to the browser’s style engine.
Official Statements & Standards Alignment
The underlying primitives making this dynamic workaround possible are part of the CSS Working Group’s ongoing modernization initiative.
- The
if()Function: Designed to bring inline conditional processing directly to property values, reducing the historical need for complex preprocessor logic or runtime script switching. - Style Queries (
style()): Originally specified as part of Container Queries Level 1 and 2, style queries allow properties to adapt based on the computed values of custom properties on parent containers. - Sibling Metrics (
sibling-index()andsibling-count()): Standardized accessor functions that expose structural position data directly to the styling layer without requiring explicit HTML markup modification.
Browser vendors note that while these features are progressively entering baseline availability across modern rendering engines, developers experimenting with advanced style query evaluations should monitor implementation updates closely.
Future Outlook
Re-implementing :nth-child() via custom properties and inline conditionals is ultimately an exercise in pushing CSS beyond its traditional declarative boundaries. It demonstrates that modern CSS is evolving into a language capable of handling complex mathematical evaluation, state management, and structural logic natively within the stylesheet.

As container style queries and inline if() functions become universally supported across all major browser engines, the boundaries between static selectors and dynamic runtime styling will continue to blur.
An Open Challenge for Developers:
If you are looking to take this architectural exploration further, consider how these principles apply in reverse. Can you adapt this dynamic implementation to support :nth-last-child()?
Hint: Success will require factoring in the total element count using sibling-count(), proving once again that with modern CSS, structural layout is limited only by imagination.
