The CSS language has evolved rapidly over recent years, transforming from a declarative styling system into a increasingly powerful visual logic engine. Despite these advances, certain structural selectors have retained historic limitations. Among these is the long-standing :nth-child() pseudo-class, a staple of element selection that allows developers to style items based on their structural index within a parent container.
While :nth-child() is ubiquitous across front-end codebases, its standard syntax—such as :nth-child(5n + 8)—is inherently static. Standard CSS rules require hardcoded integer values for its arguments. Developers cannot directly bind CSS custom properties to these formulas, rendering constructs like :nth-child(var(--A)*n + var(--B)) invalid under current specification rules. Changing the step interval or offset dynamically has traditionally required rewriting selector rules manually or relying on JavaScript DOM manipulations.
Recent specification proposals and experimental features, however, offer alternative pathways to structural selection. By pairing emerging functional additions such as inline if() conditionals, container style queries, tree-counting functions like sibling-index(), and mathematical utilities like mod(), web developers can completely re-implement the functional behavior of :nth-child() while unlocking dynamic variable control at runtime.
Addressing the Custom Variable Limitation in Structural Selectors
To understand the necessity of a dynamic alternative, it is helpful to examine the syntax limitations inherent to structural pseudo-classes. In modern web component design, layouts often rely on custom properties defined at the container level to drive responsive grids, alternating highlight patterns, or contextual list formatting.
Consider a scenario where a container defines structural parameters using CSS custom properties:
.container
--A: 5;
--B: 8;
Under standard CSS, attempting to pass these custom properties into a structural selector fails to parse:
/* Invalid syntax under standard CSS specifications */
.container > div:nth-child(var(--A)*n + var(--B))
background: red;
Because selector matching occurs early in the browser engine’s pipeline before custom property values are evaluated in cascade contexts, standard pseudo-classes cannot process var() functions as positional arguments.
To overcome this, developer experiments demonstrate that logical operations can be moved from the selector itself into computed property values. By shifting structural checks into conditional property declarations evaluated on child elements, developers can achieve dynamic, variable-driven element selection without altering the underlying HTML DOM tree structure:

<div class="container">
<div></div>
<div></div>
<div></div>
<!-- Additional child elements -->
</div>
Using this unified markup pattern, the container holds structural parameters while child elements evaluate their styling dynamically.
Single-Element Targeting: Re-Creating :nth-child(B)
The simplest structural selection pattern target a single specific child element based on its exact 1-based index, defined in traditional CSS as :nth-child(5).
To reproduce this functionality dynamically, the browser must evaluate the structural position of an element at runtime and compare it against a variable threshold. This relies on two key features: the sibling-index() function, which returns the exact numerical position of an element among its sibling group, and the experimental inline if() function combined with style() container queries.
.container
--B: 5;
.container div
background: if(style(sibling-index() = --B): red);
The inline if() syntax tests whether a specified condition evaluates to true. Within this expression, style(sibling-index() = --B) compares the structural index returned by sibling-index() directly to the value of the dynamic variable --B. If the condition evaluates to true, the inline condition returns red, applying the background color to the fifth child element exclusively.
Fallback values can be integrated directly into the inline syntax to handle unselected elements:
.container
--B: 5;
.container div
background: if(style(sibling-index() = --B): red; else: lightblue);
This inline evaluation pattern provides significant flexibility. Because style() query conditions accept flexible variable references, the logic can be expressed interchangeably depending on code formatting preferences:
.container div
background: if(style(sibling-index() = --B): red);
background: if(style(sibling-index() = var(--B)): red);
background: if(style(var(--B) = sibling-index()): red);
background: if(style(--B = sibling-index()): red);
Furthermore, this functional pattern can be applied to any valid CSS property across the stylesheet, enabling coordinated dynamic styling:
.container
--B: 5;
.container div
background: if(style(sibling-index() = --B): red; else: lightblue);
color: if(style(sibling-index() = --B): white);
While defining conditional declarations on individual properties requires repeating the evaluation expression, it establishes a functional mechanism for controlling element styling using dynamic parent variables.

Threshold and Range Selection: :nth-child(n + B) and :nth-child(-n + B)
Building upon single-element matching, structural selection frequently requires targeting ranges of elements relative to a specific index threshold.
In native CSS, selecting all elements from the fifth child onward is expressed as :nth-child(n + 5). Re-creating this dynamic selector requires adapting the equality operator within the inline conditional check to a relational inequality check:
.container
--B: 5;
.container div
background: if(style(sibling-index() >= --B): red; else: lightblue);
When an element’s index is greater than or equal to --B, the conditional expression resolves to true, styling every item from index five through the end of the container.
Conversely, targeting elements up to a specific limit—traditionally handled via :nth-child(-n + 5)—is achieved by reversing the relational operator:
.container
--B: 5;
.container div
background: if(style(sibling-index() <= --B): red; else: lightblue);
A major advantage of this approach is how cleanly it handles combined range selections. In traditional CSS, selecting elements bounded within a specific range (for instance, elements between index X and index Y) requires chaining multiple pseudo-classes:
/* Standard CSS static range selection */
div:nth-child(n + 3):nth-child(-n + 8)
background: red;
Using logical condition expressions, range matching becomes explicit and readable through compound range comparisons within a single condition:
.container
--X: 3;
--Y: 8;
.container div
background: if(style(--X <= sibling-index() <= --Y): red);
This syntax provides a clear, mathematical representation of range filtering that can be updated continuously via custom property adjustments.
Step-Based Pattern Matching: :nth-child(An)
Selecting elements based on recurring intervals—such as every third element using :nth-child(3n)—requires verifying whether an element’s structural index is an exact mathematical multiple of a step variable A.

In programmatic environments, determining multiples is typically accomplished via modulo arithmetic. Modern CSS natively supports modular mathematics through the mod() function. By checking whether mod(sibling-index(), var(--A)) yields a remainder of zero, the system accurately identifies recurring step patterns:
.container
--A: 3;
.container div
background: if(style(mod(sibling-index(), var(--A)) = 0): red);
This mathematical evaluation correctly selects the 3rd, 6th, 9th, and subsequent structural child elements. It also naturally handles standard edge cases: setting --A: 1 matches all elements equivalent to :nth-child(n), while setting --A: 2 matches even elements equivalent to :nth-child(even).
However, strict mathematical evaluation introduces an edge case when negative step values are introduced. In native CSS, passing a negative integer to :nth-child(-3n) produces no matches because structural sibling indices are strictly positive integers starting at 1. In standard mathematical modulo calculations, however, operations involving negative divisors can still evaluate to zero, leading to unintended element selections.
To align the custom implementation with official CSS selection specifications, compound logical checks can be added using the and keyword inside style():
.container
--A: 3;
.container div
background:
if(style( (mod(sibling-index(), var(--A)) = 0) and (var(--A) > 0) ): red);
By verifying both the modulo remainder and ensuring that the step multiplier --A remains positive, the custom selector logic maintains strict behavioral parity with native browser pseudo-classes.
Rebuilding the Full Structural Formula: :nth-child(An + B)
The standard linear formula for structural selection in CSS is :nth-child(An + B), where A represents the step interval, B represents the initial offset, and n represents non-negative integer values (0, 1, 2, 3...).
To solve for valid selections programmatically, the evaluation logic must verify two mathematical conditions for any given element index:
- Integer Stepping: The offset index difference
(index - B)must be evenly divisible by step intervalA. This is verified whenmod(index - B, A) = 0. - Non-Negative Range: The calculated multiplier
n = (index - B) / Amust evaluate to a non-negative value (n >= 0).
Translating these mathematical requirements directly into CSS logic yields a robust functional rule:

.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);
Edge Case Management for Static Offsets (A = 0)
While the primary equation successfully matches standard stepped offsets, a mathematical edge case occurs when --A is assigned a value of 0—representing a static single-item match equivalent to :nth-child(0n + B) or simply :nth-child(B).
In arithmetic operations, dividing by zero or calculating a modulo with a zero divisor returns NaN (Not a Number). In standard style query evaluations, NaN invalidates the condition, causing the selection check to fail entirely.
To create a robust universal implementation capable of handling --A = 0 safely alongside standard multipliers, intermediate custom properties can be introduced to normalize math evaluations before conditional checks are executed:
.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);
In this architecture, intermediate property --n calculates the base step scalar, while property --g uses sign evaluation and modulo checks to output an normalized boolean flag where 1 indicates an active selection match.
By checking if --A = 0, the system cleanly branch-evaluates single-element offsets using sign() math without attempting invalid division operations, producing a dynamic selector system capable of matching any valid structural configuration:
- Fixed Index Matching: Setting
--A: 0and--B: 7emulates:nth-child(7). - Forward Range Bounding: Setting
--A: 1and--B: 10emulates:nth-child(n + 10). - Reverse Range Bounding: Setting
--A: -1and--B: 10emulates:nth-child(-n + 10). - Regular Frequency Stepping: Setting
--A: 3and--B: 0emulates:nth-child(3n).
Architectural Implications for Modern CSS Engine Design
Re-creating structural pseudo-classes through functional CSS expressions demonstrates how far modern styling specifications have expanded. What once required rigid, static engine rules can now be modeled declaratively using inline conditions, structural tree functions, and math primitives.
Beyond serving as an instructive exploration of dynamic logic in CSS, this methodology provides practical capabilities for component design system architects. Highly customizable layout components—such as dynamic tables, data visualization containers, and customizable dashboard grids—can now adjust structural highlight patterns purely through CSS variable alterations without mutating style sheets or triggering JavaScript DOM mutations.
This pattern can also be extended to reverse structural selectors like :nth-last-child(). By replacing sibling-index() with its reverse counterpart sibling-count(), developers can build dynamic reverse-indexing algorithms using identical mathematical principles. As browser engines continue expanding support for inline conditionals and advanced container style queries, functional logic integration promises to reshape modern CSS architecture.