TMR
TMR

Reputation: 87

CSS color change on nav bar not working with class

I have a button in a nav bar, when it's clicked it should be in the "active" class. The nav bar starts out background-color transparent, when the button is clicked, the nav bar is suppose to change to background-color white (not working). When I use !important in the .active it does work, but it is white before the button is clicked (no transparent). These styles are in a media query. Is there a better way to do this?

html...

<nav class="navbar-default">
  <div class="container-fluid no-transition">
    <div value="colorChange" class="topNav">
      <div class="navbar-header">
        <button type="button" value="hideMenu" class="navbar-toggle button_container collapsed" [ngClass]="{'active': !menuCollapsed}" (click)="toggleMenu()"> 
         <div>
           <mat-icon class="menuIcon">menu</mat-icon>
         </div>      
        </button>
      </div>       
    </div>
  </div>
</nav>

SCSS...

    .topNav {
        background-color: rgba(0, 0, 0, 0) !important;
    }

   // adding !important to below turns it white, but no transparent before click

    .navbar-toggle.active, .topNav {
        background-color: white;
     }

Upvotes: 1

Views: 882

Answers (1)

So, you want than when the button has a particular class, the parent component (navbar) will have a particular style. This is actually not possible with CSS, to affect parent components. You should add the class modification to the parent instead, or maybe both, navbar+button

<nav class="navbar-default">
  <div class="container-fluid no-transition">
    <div value="colorChange" class="topNav" [ngClass]="{'active': !menuCollapsed}">
      <div class="navbar-header">
        <button type="button" value="hideMenu" class="navbar-toggle button_container collapsed" [ngClass]="{'active': !menuCollapsed}" (click)="toggleMenu()"> 
         <div>
           <mat-icon class="menuIcon">menu</mat-icon>
         </div>      
        </button>
      </div>       
    </div>
  </div>
</nav>
 .topNav {
   background-color: rgba(0, 0, 0, 0);
 }

 .topNav.active {
   background-color: white;
 }

Or, becuase you are using SCSS, you might also use:

 .topNav {
   background-color: rgba(0, 0, 0, 0);

   &.active {
      background-color: white;
   }
 }

Also, as a general rule, try to avoid !important in your CSS it is an easy solution for today but a pain for tomorrow

Upvotes: 3

Related Questions