gpt4 book ai didi

css - 基于父 mixin 控制嵌套 mixin 行为

转载 作者:行者123 更新时间:2023-11-28 15:14:17 27 4
gpt4 key购买 nike

这里有两个mixin

@mixin parent {
.parent & {
@content;
}
}

@mixin child($child) {
.#{$child} & {
@content;
}
}

两个 mixin 都可以独立工作。

正在寻找的东西:

  1. child 可以独立
  2. child mixin 也可以包含在 parent 中,但相反不应该被允许。
  3. 如果有人试图将 parent 包含到 child 中,应该是一些错误信息。
  4. 在 css 输出中 .parent 应该在 .child 之前出现(请参见下面的示例)

第 4 点示例:

.test {
//some css properties
@include parent {
@include child(childboy) {
color: red;
}
}
}

如您所见,这将产生以下输出

.childboy .parent .test {
color: red;
}

如您所见,.parent 类位于 .childboy 之后。

我们怎样才能让 .parent 类出现在 .childboy 之前

.parent .childboy .test {
color: red;
}

可以用scss做吗??请仅在 scss 中回答。

谢谢。

最佳答案

我不认为你可以那样做。

查看 this CSS-tricks post :

The & doesn't allow you to selectively traverse up your nested selector tree to a certain place and only use a small portion of the compiled parent selector that you want to use.


如果我理解正确的话,你尝试使用 SCSS 这样做的原因是因为你想将 .parent .childboy .test 选择器分组在 .test 根选择器。

这是使用 SASS 执行此操作的另一种方法:

.test {
@at-root .parent .childboy & {
color: red;
}
}

Codepen demo

注意:尾随的 & 从根向下附加选择器 - 这里,只是 .test

来自SASS docs :

The @at-root directive causes one or more rules to be emitted at the root of the document, rather than being nested beneath their parent selectors.

关于css - 基于父 mixin 控制嵌套 mixin 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47630994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com