【问题标题】:How to extend top-level selector in chain by another class如何通过另一个类扩展链中的顶级选择器
【发布时间】:2020-08-19 20:06:23
【问题描述】:

我有这个内容的 scss 定义:

.dialog {
  ...
    
  .dialog-content {
    ...
          
    .dialog-content-header {
      background-color: red;
    }
  }
}

这将导致css:

...
.dialog .dialog-content .dialog-content-header {
  background-color: red;
}

我需要找到一种方法来达到这个目的:

...
.dialog.dialog-with-train .dialog-content .dialog-content-header {
  background-color: blue;
}

额外的 .dialog-with-train 选择器应该以某种方式从 .dialog-content-header 上下文中添加。 有可能是这样的吗?

.dialog {
  ...
    
  .dialog-content {
    ...
          
    .dialog-content-header {
      background-color: red;

      @at-root getFirstItem(&).dialog-with-train getItems(&, 2, ?length?) {
        background-color: blue;
      }
    }
  }
}

在我的情况下,从 .dialog 到 .dialog-content-header 的路径非常复杂,我想以某种干净的方式进行更改,而无需修改和重复现有代码。

有什么建议吗?

EDIT1:看看https://sass-lang.com/documentation/modules/selector,有什么方法可以将选择器路径解析+组合成所需组合吗?

EDIT2:我通过使用@use "sass:string"; 对选择器进行字符串减法找到了一些解决方案。请参阅我接受的答案。

如果有更好或更清洁的解决方案我想知道。

【问题讨论】:

标签: css sass


【解决方案1】:

您需要重新考虑您的流程并使用BEM 之类的方法。

.dialog {
  
  $c: &;

  &-content {
    
    &-header {
    
      background-color: red;
      
      #{$c}--with-train & {
        background-color: blue;
      }
      
    }
    
  }
  
}

编译为:

.dialog-content-header {
  background-color: red;
}
.dialog--with-train .dialog-content-header {
  background-color: blue;
}

【讨论】:

  • 这可能适用于我从头开始编写的项目......实际上在我的情况下,“重新思考”是不可能的。该方法已给出,我无法根据您的建议更改班级命名和结构。但这个想法很有趣
【解决方案2】:

看来这个可行:

@use "sass:string";

.dialog {
  $dialog: &;
  ...
    
  .dialog-content {
    ...
          
    .dialog-content-header {
      background-color: red;

      @at-root #{$dialog}.dialog-with-train #{str-slice("#{&}", str-length("#{$dialog}") + 2)} {
        color: blue;
      }
    }
  }
}

它是如何工作的?

  1. 在上下文中定义$dialog
  2. @at-root 从根上下文生成选择器
  3. #{$dialog}.dialog-with-train 通过所需的类扩展第一个选择器
  4. #{str-slice("#{&}", str-length("#{$dialog}") + 2)} 提供当前选择器和$dialog 选择器的减法

详细说明我是如何执行“减法”的:

  1. str-length("#{$dialog}")计算$dialog选择器的字符串长度
  2. "#{&}" 以字符串形式获取当前上下文选择器
  3. #{str-slice("#{&}", str-length("#{$dialog}") + 2)} 从当前选择器获取子字符串。减法的第一个字符在 $dialog 选择器结束后的 2 个字符开始

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2013-07-18
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多