X

We would like to inform you that the domain chat-to.dev, as well as the associated project, is available for purchase. Those interested in negotiating or obtaining more information can contact us at contact@chat-to.dev.

We would like to thank everyone who has followed and supported the project so far.

1709966291

Dynamic CSS Example


example using CSS custom properties (CSS variables) and JavaScript to update those variables dynamically. ![image](https://www.kirupa.com/html5/images/dynamic_elements_created.png) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic CSS Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div id="box"></div> <button onclick="changeColor()">Change Color</button> <script src="script.js"></script> </body> </html> ``` Css(styles.css) ```css :root { --box-color: blue; } #box { width: 100px; height: 100px; background-color: var(--box-color); } ``` Javascript (script.js) ```js function changeColor() { // Get the box element var box = document.getElementById("box"); // Random color generator var randomColor = '#' + Math.floor(Math.random()*16777215).toString(16); // Update the CSS variable value box.style.setProperty('--box-color', randomColor); } ``` In this example, when you click the "Change Color" button, it calls the changeColor() function which generates a random color and applies it to the CSS variable --box-color, which is then used to set the background color of the #box element.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Donate
[2026 © Chat-to.dev]