【问题标题】:CSS specificity based on proximity to element instead of order in css codeCSS 特异性基于与元素的接近度而不是 CSS 代码中的顺序
【发布时间】:2021-10-09 03:00:15
【问题描述】:

我有一个持续的问题,我的 CSS 规则正在争夺控制权。鉴于这种无礼:

.green-theme {
    .theme-button {
        background: green;
    }
}

.blue-theme {
    .theme-button {
        background: blue;
    }
}

还有这个html:

<div class="blue-theme">
    <div class="green-theme">
        <button class="theme-button">should be green</button>
    </div>
</div>

我的按钮是蓝色的,因为蓝色主题规则出现在 css 的后面,但我希望它是绿色的,因为它更紧密地嵌套在 .green-theme 中。

这些主题是在 sass 中生成的,所以它们都是一样的。有没有办法可以翻转它,以便它从与 HTML 元素的接近度而不是 css 文件中的顺序中获取特异性?

【问题讨论】:

  • 你的意思是说如何在不编辑代码的情况下改变代码的处理方式?

标签: html css sass less css-specificity


【解决方案1】:

对于这个特定的用例,CSS variables 帮助很大。

.blue-theme {
  --btn-color: blue;
}

.green-theme {
  --btn-color: green;
}

.theme-button {
  background: var(--btn-color);
  color: white;
}
<div class="blue-theme">
    <div class="green-theme">
        <button class="theme-button">should be green</button>
    </div>
</div>

<div class="green-theme">
    <div class="blue-theme">
        <button class="theme-button">should be blue</button>
    </div>
</div>

也就是说,CSS 定义顺序和 HTML 层次结构之间的脱节听起来像是一种严重的代码异味,但在不了解更多上下文的情况下很难做出推荐。

【讨论】:

    猜你喜欢
    • 2011-11-15
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多