Animated Background Stripes Effect 12 exercises

Redefine CSS Variables to Improve Linear Gradients

Before we write code, let's think about how we can make the stripes white.

It would be a painful to have to copy a whole block of CSS just to update the color. Instead, we can use CSS variables to improve the linear gradient and make it much more reusable:

background-image: linear-gradient(

Loading solution


0:00 Before we write code, let's actually think about it. If we want to make the stripes white, we need to update the background-image linear-gradient here and change these from black to white. We want the exact same linear-gradient, but we just want to change the colors.

0:15 That feels a bit painful, to have to copy this whole block of CSS down here just to update the color and then the exact same thing for the reverse. We want all of that background gradient. We just want to change the angle here.

0:28 Instead of having triplicated linear-gradients in our CSS, what we're going to do is use CSS variables to supercharge this linear-gradient here and make it much more reusable. Let's scroll to the top, where we have our keyframe animations.

0:43 Before that, let's define some CSS variables for our stripes. It's like the default values here. I'll target the root selector. We'll define a first one called --stripes as a prefix. This one will be color. We'll define this, by default, to black. We'll have another CSS variable, --stripes-angle. The default will be what it's currently, which is -45deg.

1:10 Now, with those in place, I can update the linear-gradient here to use the angle here, var --stripes-angle. We can also update the three instances of the black color with var --stripes-color. Hopefully, everything remains the same. Yeah, it does. It still works. Now we have a way more powerful and reusable linear-gradient.

1:37 The really cool part is now all I need to do to update the color...I don't even have to write any CSS properties. We can just redefine the --stripes-color CSS variable to white. If I hit save, you can see that these two now become white. That's super-cool.

1:53 We don't write any CSS, technically. We just redefine the CSS variable's value. It's still using this exact same CSS here, but in that context, when the utility is applied, the color is updated to white. The same thing here. All we need to do is redefine the stripes-angle variable to 45 degrees instead of -45. Bang. How cool is that?