JavaScript is a powerful tool that can make your web applications more dynamic and interactive. One way you can leverage the power of JavaScript is by using it to manipulate CSS properties of HTML elements. In this blog post, we’ll explore how to use JavaScript variables in CSS to create more flexible and maintainable styles.
1. Inline CSS
The simplest way to use JavaScript variables in CSS is with inline styles. Here’s an example:
HTML:
<div id="myDiv">Hello, World!</div>
JavaScript:
const myColor = 'red';
const myFontSize = '24px';
document.getElementById('myDiv').style.color = myColor;
document.getElementById('myDiv').style.fontSize = myFontSize;
In this example, we’ve created two JavaScript variables, myColor and myFontSize, which we then use to set the color and font-size properties of an HTML element with the ID myDiv.
2. CSS Variables (Custom Properties)
Another approach is to use CSS Variables, also known as Custom Properties. This method allows you to define your variables in CSS and then manipulate their values using JavaScript. Here’s how you can do it:
HTML:
<div class="myDiv">Hello, World!</div>
CSS:
:root {
--my-color: red;
--my-font-size: 24px;
}
.myDiv {
color: var(--my-color);
font-size: var(--my-font-size);
}
JavaScript:
const myColor = 'blue';
const myFontSize = '32px';
document.documentElement.style.setProperty('--my-color', myColor);
document.documentElement.style.setProperty('--my-font-size', myFontSize);
In this example, we first define our CSS variables –my-color and –my-font-size in the :root selector. We then use the var() function to reference these variables in our CSS rules for the .myDiv class. Finally, we use JavaScript to change the values of our variables, which will update the styles of any elements with the .myDiv class.
Conclusion
Using JavaScript variables in CSS can help you create more dynamic and maintainable styles for your web applications. By leveraging the capabilities of both JavaScript and CSS, you can create powerful and interactive user experiences. Whether you prefer to use inline styles or CSS variables, both methods provide a flexible way to work with JavaScript and CSS together.