Skip to main content

Modern CSS Innovation: Rebuilding Dynamic :nth-child() Logic with Custom Properties and Inline Conditionals

For years, web developers have worked around a fundamental limitation in Cascading Style Sheets: structural pseudo-class selectors such as :nth-child() accept explicit integers and linear algebraic expressions, but they cannot accept dynamic CSS Custom Properties (var()). If a layout requires shifting structural targeting—such as highlighting every $A$-th item starting after index $B$—developers traditionally had to overwrite static rules, output repetitive generated CSS through preprocessors, or directly manipulate DOM classes using JavaScript.

However, recent advancements in CSS specifications are changing what is possible natively within stylesheets. The emergence of inline if() conditionals, container style() queries, structural tree functions like sibling-index(), and advanced mathematical functions like mod() has made it possible to completely re-implement :nth-child() logic from scratch. By synthesizing these new capabilities, developers can create fully reactive, variable-driven element selection authored directly inside pure CSS.

While re-implementing native selector behavior might at first appear redundant, it solves a long-standing architectural constraint: enabling dynamic adjustments to target parameters on the fly without needing to rewrite selector rules. Furthermore, exploring this approach provides invaluable insight into the evolving logic system of modern CSS.

To demonstrate how this mechanics works, consider a simple HTML structure consisting of a parent container holding several child <div> elements:

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <!-- ... -->
</div>

In a traditional implementation, changing selector rules based on custom properties defined on .container is impossible because pseudo-class arguments are evaluated during rule matching and cannot accept dynamic var() values:

/* Invalid CSS: pseudo-classes cannot evaluate custom variables */
.container > div:nth-child(var(--A)*n + var(--B)) 
  background: red;

By shifting the structural test inside the styling rule of child elements, CSS custom properties can control selection behavior dynamically:

.container 
  --A: 5;
  --B: 8;


.container > div 
  /* Evaluate --A and --B dynamically to determine styling */
  background: /* dynamic logic */;

:nth-child(B)

The simplest form of structural child selection targets a single element at a specific offset index $B$. In standard CSS syntax, div:nth-child(5) targets precisely the fifth child element within its parent container. In this scenario, the number 5 represents the precise structural index of the target child.

To re-implement this dynamic behavior, CSS relies on two crucial specifications: the sibling-index() function and inline if() conditional expressions integrated with container style() queries.

The sibling-index() function returns the 1-based sequential position of an element among its siblings. By evaluating this index against a custom property --B, a target element can determine its own conditional formatting directly:

Re-Implementing :nth-child() With Modern CSS | CSS-Tricks
.container 
  --B: 5;


.container div 
  background: if(style(sibling-index() = --B): red);

This syntax introduces the inline if() function, which allows conditional logic to resolve directly into property values. The conditional test occurs within the style() query function. If the structural evaluation returns true—meaning the current element’s sibling-index() matches the value declared in --B—the declared CSS value (red) is applied. If the condition evaluates to false, the declaration falls back to nothing or an optional default.

Full if/else branching is also supported, allowing explicitly defined fallback styles when an element fails the structural test:

.container 
  --B: 5;


.container div 
  background: if(style(sibling-index() = --B): red; else: lightblue);

The general structural model of the inline if() conditional operates according to a straightforward pattern:

.container div 
  background: 
    if(style( condition ): <color_if_condition_true>; 
    else: <color_if_condition_false>); 

Understanding how conditions are authored within container style() queries is key to writing these functional selectors. Depending on code structure and variable declaration, style comparisons can be written in multiple syntactically valid forms:

.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); 

This foundational technique is not restricted to background colors. The same dynamic evaluation can be mapped across any standard CSS property simultaneously:

.container 
  --B: 5;


.container div 
  background: if(style(sibling-index() = --B): red; else: lightblue);
  color: if(style(sibling-index() = --B): white);

Although repeating conditional checks across multiple CSS properties introduces some verbosity, it establishes a fully functional mechanism for dynamic element targeting. Modifying the value of --B at runtime instantly updates which DOM node receives the styling.

:nth-child(n + B)

Building upon single-element selection, the next functional pattern targets a sequence of elements beginning at a specific starting offset $B$ and continuing through all subsequent siblings. In standard CSS syntax, div:nth-child(n + 5) selects the fifth child and every element located after it.

Translating this logic into dynamic CSS requires converting equality matching into inequality evaluations. Rather than checking if sibling-index() strictly equals --B, the style query checks if the element’s index is greater than or equal to --B:

.container 
  --B: 5;


.container div 
  background: if(style(sibling-index() >= --B): red; else: lightblue);

When an element evaluates its position relative to the threshold defined by --B, any child node with a sibling-index() value equal to or exceeding --B turns red, while preceding nodes fall back to light blue.

Re-Implementing :nth-child() With Modern CSS | CSS-Tricks

:nth-child(-n + B)

The reverse of forward sequence targeting is leading element selection, represented natively as :nth-child(-n + B). This expression selects all elements from the beginning of the parent container up to and including index $B$.

Re-implementing this pattern follows the same structural inequality, simply reversing the relational comparison operator to check for index values less than or equal to --B:

.container 
  --B: 5;


.container div 
  background: if(style(sibling-index() <= --B): red; else: lightblue);

Combining forward sequence targeting (n + X) and leading sequence targeting (-n + Y) creates a bounded range selection. In static CSS, selecting elements between index $X$ and index $Y$ requires chaining two pseudo-classes together:

/* Static selection of elements within range [X, Y] */
div:nth-child(n + X):nth-child(-n + Y) 
  background: red;

Using dynamic inline conditionals, range selection becomes significantly more readable. Modern CSS style queries support compound range evaluations within a single expression:

.container 
  --X: 3;
  --Y: 8;


.container div 
  background: if(style(--X <= sibling-index() <= --Y): red);

This inline mathematical comparison evaluates whether an element’s sibling-index() sits securely within the bounds of --X and --Y. It provides a cleaner and more intuitive syntax than traditional pseudo-class chaining.

:nth-child(An)

Pattern matching based on repeating intervals requires evaluating the step factor $A$. For example, the standard selector div:nth-child(3n) selects every third element in a container (the 3rd, 6th, 9th, 12th, and so forth).

Mathematically, an element matches the pattern An if its structural index is an exact integer multiple of $A$. In computer science, determining whether one integer is a multiple of another is accomplished using the modulo operation, which calculates the remainder of integer division.

The CSS Values and Units Module introduces the native mod() function. If mod(sibling-index(), var(--A)) yields a remainder of 0, the element’s position is an exact multiple of --A:

.container 
  --A: 3;


.container div 
  background: if(style(mod(sibling-index(), var(--A)) = 0): red);

This straightforward check accurately replicates interval step matching. Setting --A to 1 targets every element (equivalent to :nth-child(n)), while setting --A to 2 selects even-numbered elements (equivalent to :nth-child(2n) or :nth-child(even)).

Re-Implementing :nth-child() With Modern CSS | CSS-Tricks

However, an edge case arises when handling negative step factors. Under standard CSS specifications, a negative step factor in :nth-child(-3n) produces no matches for positive indices, because structural positions are always positive integers. However, mathematical mod() calculations with negative values can still return 0, causing unintended elements to be selected.

To maintain full fidelity with native CSS selector specifications, the style query must verify both the modulo remainder and the sign of the step factor --A. This is achieved by combining multiple logic tests inside style() using the and operator:

.container 
  --A: 3;


.container div 
  background: 
    if(style( (mod(sibling-index(), var(--A)) = 0) and (var(--A) > 0) ): red);

By joining structural tests with and and or logical operators, dynamic CSS conditionals can handle multi-variable logical checks seamlessly.

:nth-child(An + B)

Combining step intervals and offset values yields the standard linear formula for child selection: :nth-child(An + B). This generic equation targets elements whose structural index satisfies the linear relationship:

$$textindex = A cdot n + B$$

To determine whether a specific element matches this equation, the formula can be rearranged to solve for $n$:

$$n = fractextindex – BA$$

For an element to be selected, the calculated value of $n$ must fulfill two strict mathematical criteria:

  1. Non-negativity: The value of $n$ must be greater than or equal to zero ($n ge 0$), meaning $(textindex – B) / A ge 0$.
  2. Integrality: The value of $n$ must be an integer, meaning $(textindex – B)$ must be cleanly divisible by $A$ with zero remainder: $textmod(textindex – B, A) = 0$.

Translating both mathematical requirements directly into CSS using mod(), calc(), and logical and conditions produces the generic implementation:

Re-Implementing :nth-child() With Modern CSS | CSS-Tricks
.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);

While this logic covers standard values of --A, a critical mathematical edge case occurs when --A is set to 0.

When --A equals 0, evaluating mod(index - B, 0) and dividing by zero within calc() results in an invalid NaN (Not a Number) computation, causing the overall condition to fail. In standard CSS, setting $A = 0$ collapses :nth-child(0n + B) into :nth-child(B), which should simply target the single element at index $B$.

To handle cases where --A might equal 0 without breaking the stylesheet, intermediate custom properties can be introduced to process step calculations and fallback logic using numeric functions like sign():

.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 structure, --g acts as an internal flag property. By evaluating the sign of positional offsets and verifying that $n$ contains no fractional remainder (mod(var(--n), 1)), --g resolves strictly to 1 only when an element perfectly matches the target equation.

By adjusting the --A and --B custom properties on the parent container, this single CSS declaration can dynamically replicate any structural child selector:

  • :nth-child(7) $rightarrow$ --A: 0; --B: 7;
  • :nth-child(n + 10) $rightarrow$ --A: 1; --B: 10;
  • :nth-child(-n + 10) $rightarrow$ --A: -1; --B: 10;
  • :nth-child(3n) $rightarrow$ --A: 3; --B: 0;

Dynamic Structural Styling in Modern CSS

Re-implementing :nth-child() logic using custom variables demonstrates how modern CSS is evolving from a declarative styling language into a highly capable computational environment. Selectors are ultimately conditional filters designed to isolate specific elements, and modern tools like if(), style(), sibling-index(), and mod() allow developers to express these rules programmatically.

This paradigm easily expands to reverse-order structural matching like :nth-last-child(). By pairing sibling-index() with sibling-count()—which returns the total number of sibling nodes within a parent container—developers can compute an element’s reverse index:

$$textreverse-index = textsibling-count() – textsibling-index() + 1$$

Substituting this reverse calculation into the formulas detailed above makes dynamic :nth-last-child() targeting straightforward. As browser support for CSS inline conditionals and container style query extensions continues to expand across modern web engines, these programmatic techniques open up powerful possibilities for dynamic, state-driven user interface architectures.

Basiran

Author at DesignEnt.

Flash News