[SCSS] Loop Over Data with the SCSS @each Control Directive

The SCSS @for directive is great when we know how many iterations are required and we only need 1 variable. What if we need multiple variables to iterate over data sets? Hello SCSS maps and the @each control directive! In this lesson, we’ll check out iterating with lists and looping over data sets with maps and the @each directive.

 

复制代码
// work with simple array
$superheroes: wonder-woman, spiderman, batman, superman;
@each $hero in $superheroes {
  .#{$hero}-logo {
    content: "#{$hero}";
  }
}

// we get
.wonder-woman-logo {
  content: "wonder-woman"; }

.spiderman-logo {
  content: "spiderman"; }

.batman-logo {
  content: "batman"; }

.superman-logo {
  content: "superman"; }
复制代码

 

key: value pairs using map-get():

复制代码
// work with key: value pair
$breakpoints: (sm: 375px, md: 768px, lg: 1200px);
$container-widths: (sm: 250px, md: 500px, lg: 750px);
@each $size, $bp in $breakpoints {
  @media only screen and (min-width: $bp) {
    .container-width {
      // because $breakpoints and $container-widths have the same key
      // we can use map_get(target_ary, key) to get value
      width: map_get($container-widths, $size);
    }
  }
}

// we get
@media only screen and (min-width: 375px) {
  .container-width {
    width: 250px; } }

@media only screen and (min-width: 768px) {
  .container-width {
    width: 500px; } }

@media only screen and (min-width: 1200px) {
  .container-width {
    width: 750px; } }
复制代码

 

index: values pair using nth()

复制代码
$hero-media:  (1 375px 768px crimson),
              (2 768px 1000px darkred),
              (3 1200px 1400px grey),
              (4 768px 1200px blue);

// we get

@media only screen and (min-width: 375px) and (max-width: 768px) {
  .wonder-woman {
    background-color: crimson; } }

@media only screen and (min-width: 768px) and (max-width: 1000px) {
  .spiderman {
    background-color: darkred; } }

@media only screen and (min-width: 1200px) and (max-width: 1400px) {
  .batman {
    background-color: grey; } }

@media only screen and (min-width: 768px) and (max-width: 1200px) {
  .superman {
    background-color: blue; } }
复制代码

 

posted @   Zhentiw  阅读(298)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-05-18 [PWA] 14. Loop cursor
2016-05-18 [PWA] 13. New db and object store
2016-05-18 [PWA] 12. Intro to IndexedDB
2016-05-18 [PWA] 11. Serve skeleton cache for root
点击右上角即可分享
微信分享提示