为什么div的背景颜色无法按照一般的CSS规则工作?

时间:2018-09-30 16:50:04

标签: html css

我正在做一个实验...该实验有两个div,每个div具有相同的两个类,但是它们的位置互换了。 根据一般的CSS规则,css效果仅适用于最后一个用户定义的类。

所以这是我的代码:

.green {
  background: green;
  height: 20px;
}

.red {
  background: red;
  height: 20px;
}
<div class="green red"></div>
<br>
<div class="red green"></div>

所以按照规则...在第一个div中,.red类应占主导地位,在第二个div中,.green类应占主导地位... 但是当我运行代码时,两个div都是红色的。其中第一个div应该为红色,第二个div应该为绿色。 有人可以解释吗?

1 个答案:

答案 0 :(得分:2)

根据W3C设置的规范,类的顺序不影响优先级。如果两个规则为同一元素定义了相同的属性,则最后定义的规则适用。

在您的示例中,background:redbackground:green之后,因此background:red优先。

有关更多信息,请参阅Does the order of classes listed on an item affect the CSS?