32. What are CSS variables and how do you use them?

CSS variables (also known as custom properties) allow you to store values for reuse throughout a stylesheet. They make it easier to manage and update styles.

Defining CSS variables: Variables are defined in the :root section or any selector.

:root { --primary-color: #3498db; --secondary-color: #2ecc71; }

Using CSS variables: Variables are used with the var() function.

.button { background-color: var(--primary-color); color: var(--secondary-color); }

Advantages of CSS variables:

  1. Easy style management: Variables allow for central management of values used repeatedly throughout the stylesheet.
  2. Dynamic changes: Variables can be dynamically updated using JavaScript.
  3. Inheritance: Variables can inherit values based on the context in which they are used.

Example of updating variables with JavaScript:

document.documentElement.style.setProperty('--primary-color', '#e74c3c');

CSS variables increase the flexibility and modularity of styles, making it easier to manage large projects.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.