html - 如何使父属性不覆盖后代
问题描述
我正在为我正在制作的网站使用我上网的 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;
};
}
或者那不可能?
解决方案
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>
推荐阅读
- python - 如何到达链表的头节点?
- c# - 如何将两个列表与 xunit test 进行比较
- python - 为什么我的 python 控制台日志包含换行符而不是换行符?
- c++ - 如何将特定字符视为其他值?
- javascript - 将 html 表单与提供反应性和视图模型的 JS 框架一起使用
- java - 如何在 Java 中以编程方式编写 SCM 命令
- java - 使用有效负载 Volley 发送 GET 请求
- javascript - 使用 JavaScript 更改重力表单字段的值
- php - Laravel 6 和 Vue.js 使用 vue-router 和 axios 从子组件更新记录
- java - 如何在java中传递整个类定义