Jozef Morvay
Jozef Morvay

Reputation: 131

How to override Angular material styles with global styles.css while avoiding !important?

In my angular 7 application, I am using material design. In my global styles.css file, I have some styling for material components, namely for mat icons. However, my settings are overridden by material's own style.

Using !important obviously works, but I think there is a more natural way, I just can't figure it out. In chrome dev tools, my CSS class selector simply appears below that of material design selector, and I think this means that it was simply applied sooner, and thus material style takes precedence, since they are both class selectors and should have the same priority (that is my understanding, anyway).

Relevant entry from styles.css:

.icon {
  display: inline-block;
  height: 30px;
  width: 30px;
  margin: 0 auto;
  text-align: center;
  vertical-align: middle;
}

How it appears in chrome dev tools:

.mat-icon {
    background-repeat: no-repeat;
    display: inline-block;
    fill: currentColor;
    height: 24px;
    width: 24px;
}

.icon {
    height: 30px;
    width: 30px;
    margin: 0 auto;
    text-align: center;
    vertical-align: middle;
}

Width and height are simply crossed out in my .icon style.

How can I make my style sheet be prioritized? Can I somehow specify the order in which stylesheets load, or explicitly tell angular that I want my styles take over material styles?

EDIT: added HTML where mat icons are:

<mat-toolbar color="primary">
  <div fxFlex fxLayout>
    <mat-toolbar-row fxFlex fxLayout fxLayoutGap="20px" class="navigation-items icon-group">
      <span>
        <a routerLink="/">
          <mat-icon class="icon">home</mat-icon>
          <span class="label">Home</span>
        </a>
      </span>
      <span>
        <a routerLink="/product">
          <mat-icon class="icon">bubble_chart</mat-icon>
          <span class="label">Product</span>
        </a>
      </span>
      <span>
        <a routerLink>
          <mat-icon class="icon">widgets</mat-icon>
          <span class="label">Expedition</span>
        </a>
      </span>
      <span class="spacer"></span>
      <span>
        <a routerLink (click)="logout()">
          <mat-icon class="icon">input</mat-icon>
          <span class="label">LogOut</span>
        </a>
      </span>
    </mat-toolbar-row>
  </div>
</mat-toolbar>

Upvotes: 2

Views: 1924

Answers (1)

RadekF
RadekF

Reputation: 486

It is a specificity problem. You can modify the mat-icon class directly, use id which has higher specificity or use combined selector like

.icon-group > .icon

Upvotes: 1

Related Questions