Create a gradient with a Sass loop

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 6 years ago

In this lesson, you will learn how to iteratively generate CSS selectors and attributes using Sass loops. We will create a gradient of 100 elements, each with 1% darker colour using only a couple of lines of Sass.

Instructor: [00:00] Start by creating 100 <div> elements. Each one of them is going to have a class block. We're going to put a text, "Hello," inside each one of them. I'm going to use Emmet to make it a bit faster. There we go. After we refresh, we have 100 <div> elements.

[00:21] Switch to the Sass file. Over here, create a loop which is going to go from $i=1 all the way through 100. Inside the loop, create a selector block i, which is going to create a selector for block one, block two, and so on and so forth.

[00:44] Inside of the selector, set the background to be a darkened version of the color white by i percent. It's going to be one percent darker, two percent darker, and so on and so forth. After we save it, refresh the page. We have a background which starts from white and goes all the way down to complete blackness.

[01:07] We can even verify within DevTools that each one of those elements gets a different background which is getting darker and darker if you increase the block number.