Open taralx opened 3 years ago
The target-counter()
function does exactly this in CSS, not JS. But it's currently not implemented in any browsers. https://www.w3.org/TR/css-gcpm-3/#target-counter
Hacky, suboptimal performance and unreliable for big counter values, but I guess you could create a JS function which does this:
::before
pseudo-element on the desired element, with content: counter(the-counter, the-style)
@counter-style
to define the-style
so that it produces:
n < 0
, a string with the character 0
repeated -2*n - 1
times.n = 0
, an empty stringn > 0
, a string with the character 0
repeated 2*n
times.getComputedStyle
, and divides it by the amount of pixels in 1ch
. That's the number of characters m
.m
to the desired original n
: n = m % 2 ? -(m+1)/2 : m/2
The working range is not great, because of
User agents must support representations at least 60 Unicode codepoints long, but they may choose to instead use the fallback style for representations that would be longer than 60 codepoints.
AFAIK@counter-style
is still only implemented in Firefox, but once support is broader that might work.
Chromium has an experimental implementation, you can test it with --enable-blink-features=CSSAtRuleCounterStyle
.
Currently there is no access to counter values, even with
getComputedStyle
. I'm trying to implement a system that allows cross-reference to specific elements in a list, and in order to do that I'm having to count the elements myself. Since the browser has already computed the counter value (and AFAIK counters are not reflow-sensitive, unlike page numbers), it seems like it would be useful to expose them directly.