Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

sibling-count(): count the elements sharing a parent

Use the number of direct element children, including the current element, in a CSS calculation.

Version: CSS Modules

Syntax

width: calc(sibling-count() * 10px);

sibling-count() takes no arguments and produces an integer. For an ordinary element, it counts all element children of the same parent, including the element itself. It does not count text nodes, comments or deeper descendants. The result is a number usable in calc(), unlike counter(), which produces text. Multiplying by a length supplies the unit needed for a width.

Counting follows the DOM tree, not the visual arrangement. An element hidden with display: none still belongs to the count; changing flex order does not change membership. There is no selector argument to count only matching children. Inserting or removing a sibling changes the value, so use this deliberately for layouts that depend on the whole group rather than on only its visible members.

The example starts with three direct child elements, one hidden, plus text and a comment. A nested b is not a fourth sibling. The target width is 30px, becomes 40px after an em is appended, and returns to 30px after the hidden span is removed. These computed-width reads verify recalculation after DOM changes, not merely whether the function parses.

Examples

const parent=document.createElement('div');
parent.innerHTML='text<!-- comment --><div id="target"><b>nested</b></div><span hidden></span><i></i>';
document.body.append(parent);
const target=parent.querySelector('#target');target.style.width='calc(sibling-count() * 10px)';
const width=()=>getComputedStyle(target).width;
const initial=width();parent.append(document.createElement('em'));const added=width();
parent.querySelector('[hidden]').remove();
console.log('initial='+initial+'; added='+added+'; removed-hidden='+width()+'; children='+parent.children.length+'; supported='+CSS.supports('width','calc(sibling-count() * 10px)'));

Result

initial=30px; added=40px; removed-hidden=30px; children=3; supported=true

Executed in Chromium 157.0.8103.51. This CSS Values Level 5 draft feature is not a promise of support in every browser: provide a fallback and test with @supports. Shadow-tree and pseudo-element rules have additional scope constraints and are outside this example.

Sources