skip to Main Content

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


  1. Here, you can make use of the CSS sibling combinator (~) and the :not() pseudo-class selector.

    <style>
      .chart-container {
      /* Your chart-container styles here */
     }
    
     .tile-container {
       /* Your tile-container styles here */
     }
    
     .chart-container:not(.tile-container) ~ .chart-container {
       /* Apply chart-container class only when tile-container class is not present also vise versa */
    /* Add any additional styles you need */
     }
    </style>
    
    <div class="border-solid p-2 bg-white mt-1 h-fit">
      <div class="chart-container">
        <app-angualar-component></app-angualar-component>
      </div>
     </div>
    

    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.

    Login or Signup to reply.
  2. if you want just styling, you would have to override every .chart-container styles in .tile-container like

    .chart-container{
      padding : 15px;
    }
    
    .tile-container .chart-container{
      padding : 30px !important;
    }
    

    doing this will apply tile container’s css due to higher specificity

    you can also do this instead

    <div
      class="border-solid p-2 bg-white mt-1 h-fit">
      <div [ngClass]="SOME_CONDITION ? 'tile-container' : 'chart-container'">
          <app-angualar-component></app-angualar-component>
      </div>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search