Custom properties and CSS variables are often used interchangeably when describing placeholder values in CSS despite the fact that they are different but related concepts. Preethi Sam walks through an example that demonstrates where custom properties are more suitable than variables while showcasing the greater freedom and flexibility that custom properties provide for designing complex, refined animations.
Have you ever wondered about the difference between custom properties and CSS variables? While they are often confused, they have distinct purposes. CSS variables are typically used as placeholders for values that need to be reused across a stylesheet. On the other hand, custom properties offer more flexibility and freedom for creating intricate animations.
:root {
--mix: color-mix(in srgb, #8A9B0F, #fff 25%);
}
div {
box-shadow: 0 0 15px 25px var(--mix);
}
The registration of custom properties in CSS can be done using @property
. One common use case is animating the colors of a gradient, which requires numeric interpolation that is not possible with regular CSS variables. With @property
, you can define the syntax, initial value, and inheritance behavior of a custom property, as outlined in CSS specifications.
Here’s an example of registering a custom property called --circleSize
as a percentage value that is not inherited by child elements:
@property --circleSize {
syntax: "<percentage>";
inherits: false;
initial-value: 10%;
}
div {
clip-path: circle(var(--circleSize) at center bottom);
transition: --circleSize 300ms linear;
}
section:hover div {
--circleSize: 125%;
}
By treating the custom property as a percentage value instead of a string, you can achieve effects like Material Design’s ripple effect. This demonstrates the power of using custom properties in CSS animations.
Custom properties in CSS offer a way to design elaborate animations with relatively nimble code. By leveraging the flexibility of custom properties and the @property
at-rule, you can create dynamic and visually engaging effects in your web projects.