How can I align a Material icon & header text on the same line?

Viewed 5241

I am working on an Angular Material web-page. I added a <mat-icon> next to the header text in <mat-table>. After I added the mat-icon, the icon and text are not perfectly aligned. The icon is not vertically centered and looks a little too high. The header text is not aligned with the other column text and looks a little low.

The closest I got was when I moved the mat-icon inside the tag with the text.

Here is my code

  <table mat-table [dataSource]="dataSource">
 
        <ng-container matColumnDef="column1">
           <th  mat-header-cell *matHeaderCellDef style="text-align: center !important" [attr.colspan]="2"><h2>Column 1</h2></th>
        </ng-container>

        <ng-container matColumnDef="column2">
          <th *matHeaderCellDef  style="text-align: center !important" [attr.colspan]="2">                       
            <h2><mat-icon class="pointer"  style="padding-bottom: 0px; padding-right: 1px; cursor: pointer;"         >arrow_left</mat-icon>Column 2</h2>
        </th>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="displayedGroupColumns; sticky: true"></tr>
      <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
    </table >

1 Answers

Your attention to detail is reminiscent of a customer I have at work;

To make this happen, we use position:absolute, but enclose it inside a div with position:relative so that we don't fall off the grid

relevant css:

.myCustomHeading{position:relative;padding-top:4px;}
.myIcon{position:relative;}
.mySpan{position:absolute;padding-top:2px;}

relevant HTML:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> <h2>No.</h2> </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>
      <div class='myCustomHeading'>  
        <h2><mat-icon class="pointer myIcon" >arrow_left</mat-icon>
        <span class="mySpan">Column 2</span></h2>
      </div>
    </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

complete working stackblitz available here

Related