Loops
Sass provides loops to allow iterating over elements to streamline redundant styling that you may have within your site.
#Loops#
Iterating over elements in Sass can help to streamline redundant styling that you may have within your site. If you keep images naming pretty consistent this can be very effective for listing out icons, in the case of a side navigation. There are 3 different types of looping in sass that consists of for
, each
and while
.
For
is good for iterating over a range of items, such as a way to reference the nth
child of a list of items. Below the color of the text will lighten for the list items within a set of 10.
Example of a for
:
$list-font-color: #000000
@for $i from 1 through 10
ul li:nth-child($i)
color: lighten($list-font-color, $i * 10)
Each
is handy when you know a set number of names that you will have to create over and over again. For instance, below is an example of taking a list of 3 items for a side nav and creating styles that will reference an icon for a background. For example, the first one will end up having a style called .about-nav
that will reference an icon called about-icon.png
.
Example of a each
:
@each $nav-item in blog, about, contact
.#{$nav-item}-nav
background-image: url('/images/#{$nav-item}-icon.png')
padding-left: 35px
font-size: 1em
While
is good for conditional looping over elements. For instance, if we were to re-write the first example in a while it would end up looking like the example below.
Example of a while
:
$i: 1
$list-font-color: #000000
@while $i < 11
ul li:nth-child($i)
color: lighten($list-font-color, $i * 10)
$i: $i + 1
Next: Mixins/Methods