CSS 覆盖或继承

CSS override or inheritance

我有一个关于 CSS 的非常基本的问题。如果有两个CSS个文件。

base.css 包含:

.awesome-style {
   height: 10px;
   weight: 20px;
   border: 5px;
}

child.css 包含:

@import "base.css";
.awesome-style {
   height: 15px;
   weight: 20px;
   padding: 10px;
}

当我使用 awesome-style class 时,应用的样式是什么?我的猜测是

.awesome-style {
   height: 15px;
   weight: 20px;
   border: 5px;
   padding: 10px
}

我说得对吗?有人可以给我一个关于这些“覆盖”如何工作的描述或很好的例子吗?谢谢。

您认为最终*应用于元素的样式是正确的:

.awesome-style {
   height: 15px;
   weight: 20px;
   border: 5px;
   padding: 10px
}

当您执行 @import 时,可以将其视为在要添加它的 CSS 文件中的内容之前添加 CSS。 (注:@importmust be before any other styles in your CSS

这就是它自以为是的地方。如果 CSS 文件 base.csschild.css 中都有 .awesome-style,您可能只想考虑添加与 base.css 中定义的属性不同的属性- 因为您的浏览器会读取它们,并且会应用任何不会更改或排在最后的属性。

例如,在您的示例中,您可以这样做:

base.css

.awesome-style {
   height: 10px;
   weight: 20px;
   border: 5px;
}

child.css

@import base.css
.awesome-style {
    height: 15px;
    padding: 10px
}

这是因为只有 heightpadding 发生了变化。当您考虑 CSS 文件在浏览器中的外观时,这更容易看出:

.awesome-style {
   /* browser reads this, but it will get changed */
   height: 10px;
   /* this stays the same, but will still get 'overwritten' since it's defined again in the next rule */
   weight: 20px;
   /* this doesn't get defined again, so the browser will use this */
   border: 5px;
}

.awesome-style {
   /* height changed */
   height: 15px;
   /* weight stayed the same, but is still read from this rule because it comes after the previous rule */
   weight: 20px;
   /* padding wasn't defined prior, so it will use this rule */
   padding: 10px;
}

然后这真的变成了一个关于CSS specificity

的问题

*在您当前的问题中是最终的 - 另一个规则可能会覆盖您所拥有的