Animating CSS variables (custom properties)
Unlock this video and the rest of this course by joining Frontend.FYI PRO .
JavaScript isnβt the only way to make properties change β did you forget about CSS variables? π CSS variables are a very powerful recently-ish feature of CSS. A feature that I keep discovering great use-cases for every few months.
CSS Variables (or CSS Custom Properties would be the correct name), are a way to define variables in CSS. You can then use these variables in your CSS, and change them with JavaScript. Mozilla Developer Docs does a very good job on describing them in detail. Or take a look at a video of me, using CSS variables to make a gradient follow the cursor.
In short they look like this:
:root { --header-size: 60px;}
main { padding-top: var(--header-size);}
.header { height: var(--header-size);}
With the above code we defined a variable named --header-size
with a value of 60px
, that we then use in our .header
class to define a height, but also use on the main
element to add some padding.
Good to know:
- All CSS custom properties are prefixed with
--
- You can define them on any element, just like a regular CSS property
- If you define a variable on an element, all itβs children will have access to it.
- If you override a property on a child, from that element on (including all its children) will use the new value.
Unlock the full lesson with PRO
Want to read the full lesson? Join Frontend.FYI PRO.
PRO is a one time purchase of β¬249 that gives you lifetime access to this course, any courses released in the future, and so much more!