【问题标题】:Why do style declarations inside the body selector not override Bootstrap styles?为什么正文选择器中的样式声明不会覆盖 Bootstrap 样式?
【发布时间】:2022-01-27 04:37:10
【问题描述】:

我正在学习 Bootstrap,但我不明白为什么使用正文选择器不会覆盖默认的 Bootstrap 样式。同时,我自己的样式在使用通用选择器 (*) 时适用。这是 HTML(您会看到我在样式表之前链接 Bootstrap):

body {
  font-family: 'Oxygen', sans-serif;
  font-size: 24px;
  font-weight: normal;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>David Chu's China Bistro</title>

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Oxygen:wght@300;400;700&display=swap" rel="stylesheet">

  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/style.css">
</head>

<body>
  <h1>Hello, World!</h1>
  <script src="js/bootstrap.min.js"></script>
</body>

</html>

我想设置自己的字体样式,但它不起作用。但是,它会随着通用选择器 (*) 的变化而变化。有什么问题?

【问题讨论】:

  • 那为什么不直接使用*呢?你能提供推理吗?还有~什么版本的BS?
  • 所以我正在关注 Coursera 上的“面向 Web 开发人员的 HTML、CSS 和 JavaScript”课程。老师和我一样:首先链接 Bootstrap,然后是他自己的样式表,在其中他在正文选择器中设置了一些字体属性(没有!important)并且它们实际上应用了,这意味着 Bootstrap 样式被覆盖了。可能是因为我用的是最新版的Bootstrap,他用的好像Bootstrap 3,因为课程有点过时了

标签: html css twitter-bootstrap


【解决方案1】:

这里发生的情况是,body 的 CSS 规则被其他更具体元素(如 h1)的引导属性覆盖。您的规则仅适用于正文元素中的纯文本。

CSS 以rules of specificity 运行。当特异性相等时,CSS 优先级来自:

  1. 具有style 属性的HTML 元素
  2. HTML 文档中的&lt;style&gt; 标记
  3. 外部 CSS 文档,最后加载优先

值得注意的是,任何带有 !important 声明的 CSS 属性都会提升优先级堆栈中的项目,但如果链中其他位置的竞争 CSS 属性也有 !important 声明,则可以覆盖该属性。

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 2011-11-21
    • 1970-01-01
    • 2016-04-08
    • 2015-03-31
    • 2016-08-09
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多