如何使用变量来干燥 Sass 代码?

发布于 2024-10-16 04:24:05 字数 945 浏览 2 评论 0原文

我的设计使用颜色来识别网站的各个部分。我已经放置了一个定义了颜色变量的文件,因为它们可以更改,并且很难通过 CSS 文件追踪它们。

$people: #D50000;
$galleries: #D500AA;
$projects: #D5BA00;
//etc...

我的类的名称与变量的名称相匹配。例如,导航菜单类似于:

<ul>
  <li class="people">People</div>
  <li class="galleries">Galleries</div>
  <li class="projects">Projects</div>
  <!-- etc... ->
</ul>

我发现自己在写 SASS

#nav {
  ul {
    li.people    { border-left: 5px solid $people;    }
    li.galleries { border-left: 5px solid $galleries; }
    li.projects  { border-left: 5px solid $projects;  }
  }
}

,我想把它干掉。我尝试使用 mixins,但我不知道如何告诉 SASS 查找以我传递的参数命名的变量(变量间接寻址)。我有这样的想法:

@mixin menu-states($resource) {
  li.#{$resource} a {                     // This works
    border-left: 7px solid $#{$resource}; // But this doesn't...
  }
}

有人对如何干燥这个有建议吗?谢谢。

I have a design that uses colors to identify sections of the site. I have put a file with the color variables defined, since they can change and it is difficult to track them down through the CSS files.

$people: #D50000;
$galleries: #D500AA;
$projects: #D5BA00;
//etc...

The name of my classes matches those of the variables. For example, the navigation menu is something like:

<ul>
  <li class="people">People</div>
  <li class="galleries">Galleries</div>
  <li class="projects">Projects</div>
  <!-- etc... ->
</ul>

and I find myself writing SASS like

#nav {
  ul {
    li.people    { border-left: 5px solid $people;    }
    li.galleries { border-left: 5px solid $galleries; }
    li.projects  { border-left: 5px solid $projects;  }
  }
}

which I'd like to DRY up. I have tried to use mixins, but I don't know how to tell SASS to lookup a variable named after the argument I pass (variable indirection). I have something like:

@mixin menu-states($resource) {
  li.#{$resource} a {                     // This works
    border-left: 7px solid $#{$resource}; // But this doesn't...
  }
}

Does anybody have a suggestion on how to DRY this? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

背叛残局 2024-10-23 04:24:05

这段代码对我有用

@mixin test($resource: "red"){
    $updated: unquote($resource);
    li.#{$updated} a{
        border-left: 7px solid $updated;
    }
}

this code works for me

@mixin test($resource: "red"){
    $updated: unquote($resource);
    li.#{$updated} a{
        border-left: 7px solid $updated;
    }
}
如何视而不见 2024-10-23 04:24:05

你不能这样做,但是你可以传入 2 个变量,一个用于类,另一个用于混合的颜色。

You cant do that, however you can pass in 2 variables, one for the class and another for the color to the mixin.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文