Using CSS variables (custom properties) as content property value
CSS custom properties can be used to set values on any other CSS property. Combining it with
content property to set some content in pseudo-element works as you would expect it.
// This works
--copy: 'hello world';
// This does not work :(
Turns out, if you use
setProperty to set CSS custom property, result will look something like this:
Without quotation marks, the parser is unable to determine that value is a string so it won’t render. And simply passing an actual string to
setProperty is not enough. What’s worse, using a second value in
var as fallback also won’t work since
--copy is defined (just with an invalid value).
// This still does not work :(
content: var(--copy, 'fallback');
Instead, you have to do it like this:
Notice backticks around the string. This way, quotation marks make their way into an inline style declaration and everything works. Using
"'" + 'hello' + '"' is another valid approach but I find template literals cleaner.