如何处理CSS中的级联优先级?

时间:2019-08-03 00:44:54

标签: css

假设我的应用中的链接看起来像按钮。它们是橙色的,除非它们被“禁用”(没有href):

a.button {
    background-color: orange;
}

a.button:not([href]) {
    background-color: grey;
}

现在,我不确定如何使某些按钮在其上下文中看起来有所不同,但是如何保持禁用状态不变。假设我需要将<footer>中的“按钮”设为绿色,或者-如往常一样-如果禁用则为灰色:

footer a.button {
    background-color: green;
}

问题在于此规则具有更高的优先级,因为它更具体。如何在不重复代码的情况下允许页脚中的禁用按钮仍为灰色?我知道我可以使用!important,但是请假设我的实际例子比较复杂,我想避免使用它。

2 个答案:

答案 0 :(得分:2)

使用CSS变量。您可以定义默认值,只需设置变量即可定义一个新值。

a.button {
  background-color: var(--main, orange);
}

a.button:not([href]) {
  background-color: var(--disable, grey);
}

footer#foo a.button { /*I am adding an ID to make it really more specific*/
  --main: green;
}
<a class="button">a link</a>
<a href="" class="button">a link</a>

<footer id="foo">
  <a class="button">a link</a>
  <a href="" class="button">a link</a>
</footer>

答案 1 :(得分:0)

查看http://qnimate.com/dive-into-css-specificity/,以查看CSS特异性的完整列表。

假设页脚中有多个a.button,我们将使用普通ID选择器跳过。您可以将id和属性选择器配对,使用title属性来识别所有禁用的“按钮”:

index.html

<a class="button">a link</a>
<a href="" class="button">a link</a>

<footer id="foo">
  <a class="button" title="disabled">a link</a>
  <a href="" class="button" title="disabled">a link</a>
</footer>

和styles.css

#foo a[title="disabled"] {
     color: green;
}