You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SASS循环生成合并分组的选择器,替代手写多选择器样式?

How to Group Selectors in a Sass Loop Instead of Outputting Separate Rules

Great question! The issue with your current @for loop is that each iteration outputs its own full style block, which is why you're getting separate rules for each .tlN set. To replicate your handwritten grouped selector approach, we need to first build a single list of all selectors and then apply the style to that combined list.

Here's how to do it:

// Start with an empty list to collect all our selectors
$table-selectors: ();

// Loop through each number and add both selectors to the list
@for $i from 1 through 50 {
  // Append each selector with a comma separator to build the grouped list
  $table-selectors: append($table-selectors, .tl#{$i} td, comma);
  $table-selectors: append($table-selectors, .tl#{$i} /deep/ th, comma);
}

// Apply the style rule to the complete selector list
#{$table-selectors} {
  text-align: left;
}

Why this works:

  • We initialize an empty list $table-selectors to hold all our target selectors.
  • The append() function adds each new selector to the list, using the comma argument to ensure they're separated by commas (not spaces, which would create descendant selectors instead of grouped ones).
  • After building the full list of 100 selectors (50 * 2), we use variable interpolation #{$table-selectors} to inject the entire list into a single style block.

The compiled CSS will be exactly the grouped format you want, like:

.tl1 td, .tl1 /deep/ th, .tl2 td, .tl2 /deep/ th, ..., .tl50 td, .tl50 /deep/ th {
  text-align: left;
}

This approach keeps your compiled CSS clean and matches the structure of your original handwritten code.

内容的提问来源于stack exchange,提问作者McStrudel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:30:23