Skip to content

Instantly share code, notes, and snippets.

@don1138
Created February 24, 2025 01:34
Show Gist options
  • Save don1138/3e633c853b62ddae7bff00ad94cc560b to your computer and use it in GitHub Desktop.
Save don1138/3e633c853b62ddae7bff00ad94cc560b to your computer and use it in GitHub Desktop.
Access CSS variables using Javascript
<style>
// Define your variables at the root level in CSS
// This can be in a separate CSS file, that works fine too
:root {
--color_primary: #ff0000;
}
</style>
<script>
// This function gets a CSS variable from the root document element
function getCSSVar(variable) {
return window.getComputedStyle(document.documentElement).getPropertyValue('--' + variable);
}
// Example usage
document.write('The colour primary is: ' + getCSSVar('color_primary'));
</script>
<!-- Source: https://www.reddit.com/r/webdev/comments/1iwoyw2/how_to_access_css_variables_using_javascript/ -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment