cycling through a list of colors with sass
16,878
If its possible with pure CSS, its possible with Sass. This will work with any number of colors:
http://codepen.io/cimmanon/pen/yoCDG
$colors: red, orange, yellow, green, blue, purple;
@for $i from 1 through length($colors) {
li:nth-child(#{length($colors)}n+#{$i}) {
background: nth($colors, $i)
}
}
Output:
li:nth-child(6n+1) {
background: red;
}
li:nth-child(6n+2) {
background: orange;
}
li:nth-child(6n+3) {
background: yellow;
}
li:nth-child(6n+4) {
background: green;
}
li:nth-child(6n+5) {
background: blue;
}
li:nth-child(6n+6) {
background: purple;
}
Related videos on Youtube
Comments
-
JoshuaRule over 1 year
It is possible to have list of three colors:
$color-list: x y z;
And then apply these three colors by cycling through them and adding them to on an unordered list item.
I want:
<li>row 1</li> (gets color x) <li>row 2</li> (gets color y) <li>row 3</li> (gets color z) <li>row 4</li> (gets color x)
and so on and so forth.
I had tried to use the @each (http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#each-directive) function but then it just stops applying color after the first time through the list. I want the colors to keep cycling until it runs out of list items to apply them to.
is this possible with sass?
-
steveax about 11 yearsSeems like a case for nth-child. Sass doesn't know about your markup. You could iterate through the list items with
@each
but it would be more flexible to usenth-child
.
-
-
JoshuaRule about 11 yearsI understand that method...but what I want is for it to continually loop through the colors. So on your example the 7th li would start back at red and it would do this until all of the li elements are styled.
-
cimmanon about 11 yearsAnd it does? Doesn't the demo show that? That's what
6n+1
does:(6 * n) + 1
= 1, 7, 13, 19, 25, etc. -
JoshuaRule about 11 yearsI redact my earlier comment. This works great! I understand how you have it working now.
-
BelgianCoder almost 4 yearsThis works amazingly... I needed to change the colours of carousel-items and it did the job! One question though, how to make it random? That would be the best!