CSS variables, also known as custom properties, are entities that contain specific values that can be used throughout a document. This is especially helpful for complex websites that have very large amounts of CSS with repeated values. If a color needs to be changed, it would be easier to change the variable, which will then be referenced in multiple other places, rather manually changing each one. Custom properties are subject to the cascade and inherit their value from their parent.
Basic Usage & Syntax
Declaring a CSS variable is done using a name that begins with a double hyphen (
--) and a property value that can be any valid CSS value. This is then written inside a ruleset and is defined within the scope of that ruleset. As a common best practice, custom properties are defined on the :root pseudo-class, so it can be applied globally across the HTML document (and manipulated using JS).
As with above, we’ve defined three CSS variables under
:root. In order to insert these values, CSS uses the
var() function. Typical syntax is as follows and can be coded out in the CSS file below:
var(name, value)name = the variable name (required)
value = fallback value if the variable is not found (optional)
In order to complete this task, we would need to add event listeners to the sliders and ensure the sliders are changing the correct CSS variables. We can utilize the properties of each input in order to incorporate the correct information and also use style.setProperty to change the value of the CSS variable. For the usage of the sliders, we will include two different event listeners, one to confirm the change and one to confirm the sliding effect:
While SASS also has custom variables that can be used to reference a value throughout the code, the variables in SASS are not accessible anywhere else in the code. With CSS variables, the access to the custom variables provides a more dynamic way to manipulate the page as with above. While this is just a simple way to use this capability, this opens up possibilities when it comes to larger, complex websites.
- “Using CSS custom properties (variables),” MDN Webdocs Mozilla, accessed Nov 28, 2020, https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
- “CSS Variables — The var() Function,” w3schools, accessed Nov 28, 2020, https://www.w3schools.com/css/css3_variables.asp