Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Created January 15, 2024 07:11
Show Gist options
  • Save ryanmorr/4fdce0c78976942097b803bfd6405a85 to your computer and use it in GitHub Desktop.
Save ryanmorr/4fdce0c78976942097b803bfd6405a85 to your computer and use it in GitHub Desktop.
Define JSON data within CSS
// I have no idea how practical this is, but I can't help but appreciate hacks like this
// Found it here: https://github.com/uikit/uikit/blob/fc644b5107c47c7242436c782dd935a374ab399e/src/js/util/style.js#L65
const vars = {};
function getCSSVar(name) {
if (!(name in vars)) {
const el = document.createElement('div');
document.documentElement.appendChild(el);
el.classList.add(`var-${name}`);
try {
const data = window.getComputedStyle(el, ':before').content.replace(/^["'](.*)["']$/, '$1');
vars[name] = JSON.parse(data);
} catch (e) {}
document.documentElement.removeChild(el);
}
return vars[name];
}
// Usage in CSS: .var-name:before { content:"xyz" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment