Skip to content

Instantly share code, notes, and snippets.

@maradondt
Created April 13, 2022 10:14
Show Gist options
  • Save maradondt/9ac5027533d20fd0dba1be7fcc96622f to your computer and use it in GitHub Desktop.
Save maradondt/9ac5027533d20fd0dba1be7fcc96622f to your computer and use it in GitHub Desktop.
added css vars from js
const addStyles = (style: HTMLStyleElement) => {
document.querySelector('head')?.appendChild(style);
};
const createStyleVariablesFromObject = (prefix: string, vars: { [k: string]: string }) => {
const style = document.createElement('style');
style.textContent = `
:root {
${Object.entries(vars)
.map(([name, value]) => `--${prefix}-${name}: ${value}`)
.join(';')}
}
`;
return style;
};
export const addVarsInRoot = (prefix: string, vars: { [k: string]: string }) => {
const style = createStyleVariablesFromObject(prefix, vars);
addStyles(style);
};
// EXAMPLE:
// export const SHADOWS = {
// MAIN0: '0px 2px 4px 2px rgba(108, 108, 108, 0.1)',
// MAIN1: '0px 0px 1px rgba(0, 0, 0, 0.12), 0px 4px 8px -2px rgba(0, 0, 0, 0.12)',
// MAIN2: '0px 0px 1px rgba(0, 0, 0, 0.12), 0px 8px 16px -4px rgba(0, 0, 0, 0.12)',
// };
//
// addVarsInRoot('shadow', SHADOWS);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment