【问题标题】:why div's background color is not working as per general css rule? [duplicate]为什么 div 的背景颜色不能按照一般的 css 规则工作? [复制]
【发布时间】:2018-09-30 16:50:03
【问题描述】:

我正在做一个实验......这个实验有两个 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 应该是绿色。 谁能解释一下?

【问题讨论】:

  • 最后一个css规则支配
  • 详细说明@Piterden 的评论:最后,他是指在css 文件中声明的最后一个,而不是您添加到元素的最后一个类。 class 属性中的声明顺序无关紧要。
  • 没错,thanx,@autra

标签: html css


【解决方案1】:

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

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

更多信息请参考Does the order of classes listed on an item affect the CSS?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2021-04-22
    • 2021-11-28
    • 2013-09-17
    • 2020-03-15
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    相关资源
    最近更新 更多