





Here is a little experiment I did when I was fiddling around with adjusting element properties using Sass in a for-loop.

See the Pen Sass coloring + expanding shadows by Creative Punch (@CreativePunch) on CodePen.

The HTML

This effect can easily be done in a few simple lines. In this particular example I created a header element with a number of div child elements.

<header> <div></div> <div></div> <div></div> ... </header>

Let’s get Sassy

We define a variable $elements which equals the number of child elements in our header element. We use this variable in a for-loop

$elements: 10 @for $i from 0 to $elements

Next we use the iterator $i to calculate colors in this for-loop

@for $i from 0 to $elements $red: ($i*10)+150 $green: (($i*10)+150)/2 $blue: (($i*10)+150)/2

This will make our colors brighter. Our minimal value for $red will be 150. Its maximal value will be 250 since there are 10 elements. You will want to adjust these values according to your number of elements.

Next, we will use the $i variable to generate CSS selectors. We will make our variable be outputted as text so it is usable in the selector by wrapping it like this

#{$VARIABLE}

Knowing this, we will output our selectors inside of our loop like this:







header div:nth-child(#{$i})

Next we will define a width and height for our elements and add the color. We also would like it to have a box-shadow. Sass can even do in-line calculations which we will use for our shadow values!

header div:nth-child(#{$i}) background: rgb($red,$green,$blue) width: 100% height: 30px box-shadow: 0 -1px #{($elements - $i)*2}px rgba(0,0,0,0.7)

The result

The full generated CSS will look like this

header div:nth-child(0) { background: #964b4b; width: 100%; height: 30px; box-shadow: 0 -1px 20px rgba(0, 0, 0, 0.7); } header div:nth-child(1) { background: #a05050; width: 100%; height: 30px; box-shadow: 0 -1px 18px rgba(0, 0, 0, 0.7); } header div:nth-child(2) { background: #aa5555; width: 100%; height: 30px; box-shadow: 0 -1px 16px rgba(0, 0, 0, 0.7); } header div:nth-child(3) { background: #b45a5a; width: 100%; height: 30px; box-shadow: 0 -1px 14px rgba(0, 0, 0, 0.7); } header div:nth-child(4) { background: #be5f5f; width: 100%; height: 30px; box-shadow: 0 -1px 12px rgba(0, 0, 0, 0.7); } header div:nth-child(5) { background: #c86464; width: 100%; height: 30px; box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.7); } header div:nth-child(6) { background: #d26969; width: 100%; height: 30px; box-shadow: 0 -1px 8px rgba(0, 0, 0, 0.7); } header div:nth-child(7) { background: #dc6e6e; width: 100%; height: 30px; box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.7); } header div:nth-child(8) { background: #e67373; width: 100%; height: 30px; box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.7); } header div:nth-child(9) { background: #f07878; width: 100%; height: 30px; box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.7); }

We did all that with just 10 lines of Sass (white lines not included). How awesome is that?