英文:
How can I apply CSS to any div except those inside a parent div with a specific class?
问题
我有一个应用于所有div
的全局CSS,但我想对具有特定类的父div
内的div
做出例外,示例中的类是should-not-apply
。
div:not(.should-not-apply) {
font-size: 20px !important;
font-weight: 500 !important;
}
我已经研究了:not 选择器,但它仅适用于元素,而不适用于它们的子元素。
我之所以需要以这种方式修改CSS内容而不是覆盖,是因为我正在使用服务器端渲染(SSR)创建页面,并且预定义的CSS内容会在此处的CSS文件之前应用,但我希望使用来自SSR 的CSS内容,而不是全局的CSS。
如何实现这样的任务?
英文:
I have a global CSS that applies to all div, but I want to make an exception for the divs inside a parent div with a specific class, which in the example is should-not-apply
class.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
div {
font-size: 20px !important;
font-weight: 500 !important;
}
<!-- language: lang-html -->
<div>
<div>
0 should apply
</div>
<div class="should-not-apply">
<div>
<div>
1.1 should not apply
</div>
<div>
1.2 should not apply
</div>
</div>
<div>
2 should not apply
</div>
</div>
<div>
3 should apply
</div>
<div>
4 should apply
</div>
</div>
<!-- end snippet -->
I have looked into :not Selector, but it only applies to the elements, not their children.
The reason I need to modify the CSS content this way instead of overwriting, because I am creating the page with server-side rendering (SSR) with predefined CSS content, which gets applied before the CSS file here, but I want the CSS content from that SSR instead of this global one.
How can I achieve such task?
答案1
得分: 0
div:not(.should-not-apply > div) {
font-size: 20px !important;
font-weight: 500 !important;
}
英文:
It should work:
div:not(.should-not-apply > div) {
font-size: 20px !important;
font-weight: 500 !important;
}
答案2
得分: 0
<!-- 开始代码片段: js 隐藏: false 控制台: true Babel: false -->
<!-- 语言: lang-css -->
:not(.should-not-apply div) {
font-size: 20px;
font-weight: 500;
}
div {
font-size: initial;
font-weight: initial;
}
<!-- 语言: lang-html -->
<div>
<div>
0 应用
</div>
<div class="should-not-apply">
<div>
<div>
1.1 不应用
</div>
<div>
1.2 不应用
</div>
</div>
<div>
2 不应用
</div>
</div>
<div>
3 应用
</div>
<div>
4 应用
</div>
</div>
<!-- 结束代码片段 -->
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
:not(.should-not-apply div) {
font-size: 20px;
font-weight: 500;
}
div {
font-size: initial;
font-weight: initial;
}
<!-- language: lang-html -->
<div>
<div>
0 should apply
</div>
<div class="should-not-apply">
<div>
<div>
1.1 should not apply
</div>
<div>
1.2 should not apply
</div>
</div>
<div>
2 should not apply
</div>
</div>
<div>
3 should apply
</div>
<div>
4 should apply
</div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论