Home

The CSS content property takes a string

A little “this should work, why is it not working?” gotcha - the CSS content property takes a string (among other things), not a number.

I was trying to display a CSS variable in an ::after pseudo-element like so:

let notificationCount = title.match(TITLE_NOTIFICATION_RE)[1]
document.body.style.setProperty('--notification-count', notificationCount)
.NotificationCount::after {
  content: var(--notification-count);
}

This should obviously work, right? But nothing was appearing.

The fix ended up being putting quotes around the declaration of the CSS variable’s value, making it a string, a distinction which is easy to miss when dynamically defining a variable from JavaScript:

document.body.style.setProperty('--notification-count', `"${notificationCount}"`)

There is also a trick using counter-reset and content: counter() if you specifically need to display a CSS variable containing a number.

created