I am new to CSS. In one use case I need to apply a CSS class, only when another is not present.
<div
class="border-solid p-2 bg-white mt-1 h-fit"
[ngClass]="SOME_CONDITION ? 'tile-container' : ''"
>
<div class = 'chart-container'>
<app-angualar-component></app-angualar-component>
</div>
</div>
If tile-container class is present then chart-container class should not get applied and vice versa if tile-container is not present then chart-container class should get applied.
I need to achieve this via CSS only.
It looks a very common use case, but I didn’t find any open/closed question which is getting fit into current use case.
How can I do it?
2
Answers
Here, you can make use of the CSS sibling combinator (~) and the :not() pseudo-class selector.
In the above code, the ‘chart-container:not(.tile-container) ~ .chart-container’ selector targets elements with the chart-container class that do not have the tile-container class as their previous sibling. This way, when the tile-container class is present, the chart-container class will not be applied, and vice versa.
if you want just styling, you would have to override every
.chart-container
styles in.tile-container
likedoing this will apply tile container’s css due to higher specificity
you can also do this instead