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.
div {
font-size: 20px !important;
font-weight: 500 !important;
}
<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>
I have looked into :not Selector but it only applies to the elements, not their children.
The reason I need to modify the css this way instead of overwriting because I am creating the page with Server Side Rendering with predefined css, which gets applied before the css file here but I want the css from that SSR instead of this global one.
How can I achieve such task?
3
Answers
To make an exception for the div elements inside a parent div with a specific class, you can use CSS descendant selectors and override the global styles. Here’s an example of how you can achieve this:
In this example, the .should-not-apply div selector targets all div elements that are descendants of an element with the class .should-not-apply. By resetting the font-size and font-weight properties to their initial values, you effectively override the global styles and make them not apply within that specific context.
With this CSS code, the div elements inside the .should-not-apply parent div will not inherit the font styles defined globally and will instead use their default values.
It should work: