css - SASS/SCSS - 制作一个将“退出”以修改选择器父级的选择器
问题描述
我想在单个代码块中包含选择器的所有相关样式,以便可以轻松引用它。
在我的应用程序中,选择器的有效样式将根据其所在的上下文发生巨大变化。例如,让我们假设这个 CSS:
.container.theme-dark .message
{
font-size: 16px;
background-color: black;
color: white;
}
.container.theme-light .message
{
font-size: 16px;
background-color: white;
color: black;
}
然后,假设我有以下 HTML:
<div>
<div class="container theme-dark">
<div class="message">Hello World</div>
</div>
<div class="container theme-light">
<div class="message">Hello World</div>
</div>
</div>
现在使用 SCSS,我会像这样创建相关的 CSS:
.container
{
&.theme-dark
{
.message
{
background-color: black;
color: white;
}
}
&.theme-light
{
.message
{
background-color: white;
color: black;
}
}
.message
{
font-size: 16px;
}
}
我希望能够使用 SCSS 生成该 CSS,并将 .message 元素的所有相关信息放在一个地方。例如(使用一个虚构的 $ 运算符来完成我想要完成的工作):
.container
{
.message
{
font-size: 16px;
$.theme-light
{
background-color: white;
color: black;
}
$.theme-dark
{
background-color: black;
color: white;
}
}
}
有任何想法吗?
解决方案
我想这可能会奏效,就像你说的那样?(如果您将每个示例标记为“理想的 CSS 输出”、“当前的 SCSS、太多的.message
块”和“理想的 SCSS 格式”,这将对我有所帮助)
.container
{
@at-root .message
{
font-size: 16px;
.theme-light &
{
background-color: white;
color: black;
}
.theme-dark &
{
background-color: black;
color: white;
}
}
}
有了@at-root
那里,它会生成.theme-light .message
,这对于某些用途来说可能过于宽松,所以不是理想的解决方案......
https://codepen.io/anon/pen/ZMxjEq
基本上&
被完整的树路径替换,所以.container .message
,没有@at-root
,将生成.theme-light .container .message
,这不适用于结构。也许还要考虑这一点,这是一个合理的妥协,我会说:
.container
{
.message
{
font-size: 16px;
}
@at-root .message
{
.theme-dark
{
...
}
.theme-light
{
...
}
}
}
这显然是一种 hacky 解决方案,但显然有效
推荐阅读
- android - 如何获取已发送的 SMS 消息?
- python - 对于所有可能的行和列组合,根据它们的相对距离聚合 pandas 数据框的值
- c# - Puppeteer Sharp - js 运行完成后获取 html
- machine-learning - 无法理解 YOLOv4 架构
- ios - 在 Else 块中访问 ObservableObject 时视图不更新
- python - Python 结构模式匹配
- javascript - 如何在视频停止播放后隐藏或淡出 HTML 视频,然后显示下面的 H1 标题标题
- apache-kafka - 为什么Kaka Streams repartition topic的retention.ms默认设置为-1?这不是在重新分区主题中无限保留消息吗?
- php - 尝试发布 Laravel 包时无法找到可发布的资源
- javascript - 如何让 Javascript 循环在开始下一个迭代之前等待现有迭代完成?