css - Sass 返回嵌套问题

标签 css sass css-selectors

我正在尝试弄清楚如何将嵌套专门返回到我所在的 css 嵌套的父级。意思是,我当前的设置是一个跨度到 before 伪类的父类。我需要根据父项上的修饰符更改伪样式。如果我这样做:

.parent {
    span {
       &:before {
          // styles

          .modifier & {
             // Other styles
          }
       }
   }
}

输出是.modifier .parent span:before 我需要的是.parent.modifier span:before

有没有办法在不向父级添加修饰符并再次指向伪的情况下执行此操作?这是我想避免的。

.parent {
    span {
       &:before {
          // styles
       }
   }
   &.modifier {
       span {
          &:before {
             // Other Styles
          }
       }    
   }
}

最佳答案

这当然是可能的,它确实需要使用一些鲜为人知的sass函数@at-root&ersand和字符串插值#{

基本上它按以下方式工作;

  1. 使用 @at-root 跳出类,跳到“根”。
  2. 我们将我们的类(class)放在这之后,我使用了 .--modifer-is-red
  3. 我们通过使用 &#{&} 的插值附加跳出的类。

Live Example

为清楚起见而使用的示例

.parent {
  span {
     &:before {
      // styles
      color: black;

      // Modifiers attached to the parent
      @at-root .--modifier-is-red#{&} {
        color: red;
      }
    }
  }
}

// output
// .--modifier-is-red.parent span:before {
//   color: red;
// }

反射(reflect)您的代码的准确示例

.parent {
    span {
       &:before {
          // styles
          @at-root .modifier#{&} {
             // Other styles
          }
       }
   }
}

这有一些限制,修饰符在输出中放在父级之前看起来确实有点奇怪,但浏览器并不介意。

希望这能解决您的问题。

关于css - Sass 返回嵌套问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41641410/

相关文章:

html - CSS 在 href 悬停时显示子菜单

css - Container/Wrapper Div 不包含所有内容?

html - 使用 css 获取 td 标签中的前几行

jquery - 最后一列标题文本使用数据表垂直对齐

javascript - 剪切路径圆弧形状

css - 液体 SCSS 文件中的 if 语句 (Slate/Shopify)

css - Sass (.scss) 文件的 Aptana Studio 3 代码辅助

css - 如果 LESS Mixin 在其内部,则阻止应用它?

jquery - 本地存储和 Jquery

html - 使用 CSS 动画旋转单词。我如何停在最后一个字?