使用自定义 CSS 覆盖默认值 bootstrap css 仅适用于 !important 规则

Overwriting default bootstrap css with custom CSS only works with !important rule

基本上我已经解决了我的问题,但我想了解为什么我需要这样做我是怎么做的。因此,我创建了一个简短示例,可在 https://jsfiddle.net/herbert_hinterberger/9x22u934/

现在我想问为什么我需要在里面使用 !important 规则

.navbar-brand {
    color: #eae8e8 !important;
}

更改 .navbar-brand 的颜色?据我了解,自定义 CSS 应该覆盖 bootstrap 默认 css 规则。但是出于任何原因,如果我不使用 !important 规则,bootstrap 默认 CSS 规则将在自定义 CSS 规则之前应用。参见

任何人都可以解释为什么我需要在这里使用 !important 规则吗?

此致, 赫伯特

您不需要每次都使用 !important

规则是,css 以后来的就拿。所以,如果你有

.aClass {
    color:red;
}

red.css

.aClass {
    color:blue;
}

blue.css,
并且在 red.css 之后包含 blue.css,具有 aClass 的文本将为蓝色。

只有当您希望一条规则覆盖其他所有规则时才使用 !important


编辑:在OP的评论之后,这个问题的实际答案是这样的。

bootstrap.css 文件中,我们有类似的内容:

.navbar-default .navbar-brand {
    color: #hashtag;
}

因此,当您这样做时:

.navbar-brand {
    color: #newHashtag;
}

它不会改变 .navbar-default 调用的 .navbar-brand 的颜色(您在 HTML 中使用此 class 到 .navbar-default) .这里,.navbar-brand.navbar-default 的后代。但是,当您输入 !important 时,它会告诉所有 .navbar-brand 更改颜色。

因此,如果您确实想更改 .navbar-brand 的颜色,请尝试以下操作:

.navbar-default .navbar-brand {
    color: #newHashtag;
}

有关详细信息,请阅读 CSS 中的 后代选择器组合器

当你想用你自己的覆盖 bootstrap CSS 时,你需要在 bootstrap 之后包含你的自定义 CSS。

<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
</head>

这是因为 css 选择器 bootstrap 使用的“.navbar-header .navbar-brand”比你的“.navbar-brand”更具体 看到这个 http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/ 试试这个

.navbar-header .navbar-brand {
  color: #eae8e8;
}

这是对您的问题的最佳解释

案例:1

<!-- HTML -->
<div class="blue box"></div>

/*CSS*/
div {
  height: 200px;
  width: 200px;
}

/*The Battle*/
.blue {
  background-color: blue;
}

.box {
  background-color: red;
}

Battle中如何取胜?显然是最后一个,即

.box {
      background-color: red;
    }

背景颜色红色应用于 div

其他 Anwsers 解释了这种情况,在 bootstrap.css 之后编写自定义 css 文件,它会覆盖 bootstrap 样式

案例:2

ID 对比 Class

<!-- HTML -->
<div class="box" id="box"></div>
    /*CSS*/
div {
  height: 200px;
  width: 200px;
}

/*The Battle*/
#box {
  background-color: blue;
}

.box {
  background-color: red;
}

如何获胜?显然id Win,根据Rules of Specificity

,Id被宣布为赢家

元素根据特异性得分

  • inline-style = 1000 点(由css特异性决定)
  • ID值100分。
  • Classes值10分。
  • 元素值 1 分。

示例:

#content .sidebar .module li a{}

分数是:

#content =100; .sidebar, .module = 10 +10; li, a = 1+1

总计:122

如果我们在前面加上一个id如下我们可以覆盖上面提到的样式因为下面提到的样式的分数是222

#main-container #content .sidebar .module li a{}