Created
February 24, 2025 01:34
-
-
Save don1138/3e633c853b62ddae7bff00ad94cc560b to your computer and use it in GitHub Desktop.
Access CSS variables using Javascript
This file contains hidden or 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
<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