首页 > 解决方案 > 如何使父属性不覆盖后代

问题描述

我正在为我正在制作的网站使用我上网的 css 文件,但我只是将一些组件嵌入到网站中。这个 css 文件使用全局样式,它们覆盖了我网站上的所有全局样式。我想我只需包装全局样式并使它们成为一个类的后代,然后将其作为我的组件的父类。这是我所说的一个例子

h1 {
  color: red;
}

.text {
  color: blue;
}

但是现在我h1在页面上的所有标签都变成了红色。我决定包装所有全局样式并使其只有某个类的后代会受到该样式的影响。这是新的 CSS 的样子

.parent-class h1 {
  color: red;
}

.text {
  color: blue;
}

并使我的 html 看起来像这样

<h1>This should not be affected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>How's it going</h1>
</div>

第一部分确实有效。我的顶部h1不受全局 css 的影响,就像以前一样。

但这是我遇到的问题。以前,这个text类是压倒全局h1风格的,我的Hello最终是蓝色的,而我的How's it going则是红色的。现在h1已经被父母包裹了,Hello也以红色收场。

我知道父样式首先出现在 css 文件中,所以我认为这不是先渲染什么的问题。另外,我知道一切都在使用类,而不是 ID,因此也不会发生优先级问题。

我猜这是因为.parent-class h1现在有两条规则而.text只有一条。如果是这种情况,有没有办法缓解这个问题?

我可以做的一件事就是将父级包裹在子级周围,例如.parent-class .text,但是我在网上找到的 css 文件有接近 25,000 行代码,而全局规则只有大约 300 行,所以这将非常耗时,因为有我需要更改数千个课程。

有没有其他方法可以解决这个问题?如果没有,有没有办法以这样的方式将父规则包装在多个代码块周围

.parent-class {
  .text {
    color:blue; 
  };
  h1 {
    color: red;
  };
}

或者那不可能?

标签: htmlcsscss-selectors

解决方案


Make sure your second selector is having the same (o higher) specifity by combining it with something else. You can for example add nth-child(n) which will not change the behavior of your selector but simply increase its specificity:

.parent-class h1 {
  color: red;
}

.text:nth-child(n) {
  color: blue;
}
<h1>This should not be affected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>How's it going</h1>
</div>

You can also duplicate the class:

.parent-class h1 {
  color: red;
}

.text.text {
  color: blue;
}
<h1>This should not be affected by any css</h1>
<div class="parent-class">
  <h1 class="text">Hello</h1>
  <h1>How's it going</h1>
</div>


推荐阅读