CKTIS / CSS
counter() — one counter value
`counter()` converts the innermost value of a named CSS counter to text or an image using a selected counter style.
Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required
Syntax
counter( <counter-name>, <counter-style>? )counter() converts the innermost value of a named CSS counter to text or an image using a selected counter style.
The example renders counter(step) as 7 and counter(step, decimal-leading-zero) as 07; the second pseudo-element being twice as wide proves the leading zero was present in genuinely generated content.
Grammar: counter( <counter-name>, <counter-style>? ).
The second argument is optional and defaults to decimal. The function reads the nearest counter of that name, not all scopes combined, and the name cannot be none. If no such counter exists, the browser instantiates one at 0. Use it in generated content or markers with deliberately placed resets and increments.
Examples
const style = document.createElement('style');
style.textContent = '.plain,.padded{display:inline-block;font:20px monospace}.plain{counter-reset:step 7}.padded{counter-reset:step 7}.plain::before{content:counter(step)}.padded::before{content:counter(step, decimal-leading-zero)}';
const plain = document.createElement('span'); plain.className = 'plain';
const padded = document.createElement('span'); padded.className = 'padded';
document.head.append(style); document.body.append(plain, padded);
const one = plain.getBoundingClientRect().width;
const two = padded.getBoundingClientRect().width;
console.log('decimal-glyphs=' + Math.round(one / (one || 1)) + '; leading-zero-glyphs=' + Math.round(two / (one || 1)) + '; width-ratio=' + (two / one).toFixed(2));Result
decimal-glyphs=1; leading-zero-glyphs=2; width-ratio=2.00
`counter()` converts the innermost value of a named CSS counter to text or an image using a selected counter style.