Directly controlling Sass variables from JavaScript is not straightforward because Sass, a CSS preprocessor, is compiled into CSS on the server-side or during the build process. This means all variables and logic are converted into static CSS code before being sent to the browser. However, we can indirectly achieve dynamic control over Sass variables through several methods:
Method One: Using CSS Variables with Sass
The most common and recommended approach is to use CSS custom properties (also known as CSS variables), which can be controlled by JavaScript at runtime and used in Sass.
- Define CSS variables: Define some base variables in CSS (or Sass).
scss:root { --primary-color: #ff6347; // Default color } body { background-color: var(--primary-color); }
- Modify variables via JavaScript: You can dynamically change the values of these variables in JavaScript.
javascriptdocument.documentElement.style.setProperty('--primary-color', '#4CAF50');
This method is simple and aligns with modern web development standards, supporting dynamic style changes in the browser.
Method Two: Dynamically Adding Styles
If you need to dynamically generate style rules from JavaScript, you can directly add a <style> tag to the page or modify existing CSS style sheets.
- Dynamically create styles:
javascriptconst style = document.createElement('style'); document.head.appendChild(style); style.innerHTML = `body { background-color: ${yourDynamicColor}; }`;
Method Three: Using Preprocessors and Build Tools
If your project uses build tools (such as Webpack), you can modify Sass variables during the build process using environment variables or configuration files.
- Use environment variables in Sass:
scss// In Sass file $primary-color: #{env('PRIMARY_COLOR', '#ff6347')}; body { background-color: $primary-color; }
- Set environment variables in the build configuration (for example, with Webpack):
javascriptnew webpack.DefinePlugin({ 'process.env.PRIMARY_COLOR': JSON.stringify('#4CAF50') });
This method is more suitable for scenarios where styles or themes are determined during the build.
In Summary:
Although you cannot directly modify Sass variables from JavaScript, you can achieve similar effects using CSS variables, dynamically created styles, or build-time configuration. Each method has its own use cases, and you can choose the most suitable one based on your project's requirements and environment.