Created
January 15, 2024 07:11
-
-
Save ryanmorr/4fdce0c78976942097b803bfd6405a85 to your computer and use it in GitHub Desktop.
Define JSON data within CSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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