Sass循环以及实际应用 Dec 8 2024 笔记 0 comment Sass在提供列表(List)和集合(map)这些复杂结构的同时也提供了遍历它们的方法:sass loop。常见的循环有三种: - @each - @for - @while ### each `@each`是最Sass常见的循环方式。语法简洁,可以遍历列表或者集合,但在语法上有一些差异。 $colors:('tomato','blue','green'); //@each遍历列表 @each $color in $colors { .section-#{$color} { background-color: $color; } } //输出的css .section_tomato { background: "tomato"; } .section_blue { background: "blue"; } .section_green { background: "green"; } 当遍历集合时,使用`$key`,`$value`组合来确定变量的名称一致性,集合在实际应用中更具灵活性。 $themes:( "top":"tomato",; "middle":"blue"; "bottom":"green"; ); @each $key,$value in $themes{ .section_#{$key} { background-color: $value; } } //输出的css .section_top { background: "tomato"; } .section_middle { background: "blue"; } .section_bottom { background: "green"; } ### for `@for`循环对于伪类`:nth-of-type`更加友好,它可以更加灵活的指定遍历范围。 //在伪类中使用for @for $i from 1 through 6{ .foo:nth-of-type{ background:hsl($i * 36, 50%, 50%); } } //输出的css .foo:nth-of-type(1) { background: hsl(36, 50%, 50%); } .foo:nth-of-type(2) { background: hsl(72, 50%, 50%); } .foo:nth-of-type(3) { background: hsl(108, 50%, 50%); } .foo:nth-of-type(4) { background: hsl(144, 50%, 50%); } .foo:nth-of-type(5) { background: hsl(180, 50%, 50%); } .foo:nth-of-type(6) { background: hsl(216, 50%, 50%); } `@each`和`@for`的格式规范: - @each和@for前添加空行 - 除非下一行是右闭大括号(`}`),否则在所有右闭大括号(`}`)后面添加新行。 ### while 不建议使用`@while`循环。 本文由 yuin 创作,本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。