Source:  Twitter logo

I am trying to align one of the headers in my table right. I tried:

.header-align-right {
    display: flex;
    justify-content: flex-end;
  }

In a class and add it to the mat-header-cell. This aligned the text right but also added weird spacings to the element that made it not aligned with the rest of the headers. Tried it also without the display:flex but that did nothing.

<ng-container matColumnDef="Number">
        <th mat-header-cell *matHeaderCellDef mat-sort-header class="header-align-right">Number</th>
        <td mat-cell *matCellDef="let row" align="right">{{row.Number}}</td>
        <td mat-footer-cell *matFooterCellDef></td>
</ng-conIainer>

As you see i align right the content of the cell and I would like to align the header as well.

Cell alignment is done by default via flexbox when using <mat-header-cell> and <mat-cell>, but not when using <th mat-header-cell> and <td mat-cell>. When using the table elements, the alignment is done with text-align. If you force flexbox all of the time, the table cells using th and td have the possibility of losing vertical alignment with the rest of the table.

I found that a combination of setting text-align: right and setting justify-content: flex-end works best. That way, elements with display:table-cell use text-align, and elements with display:flex use justify-content.

For your example:

.header-align-right {
  text-align: right;
  justify-content: flex-end;
}

To get the arrow to show up before the header, you should use the arrowPosition attribute.

Also, I would suggest using the auto-added column class (.mat-column- + case-sensitive value of matColumnDef) instead of adding class="header-align-right". That will align the headers, cells, and footers. So here's what I would suggest:

.mat-column-Number {
  text-align: right;
  justify-content: flex-end;
}
<ng-container matColumnDef="Number">
  <th mat-header-cell *matHeaderCellDef mat-sort-header arrowPosition="before">Number</th>
  <td mat-cell *matCellDef="let row">{{row.Number}}</td>
  <td mat-footer-cell *matFooterCellDef></td>
</ng-conIainer>
30 users liked answer #0dislike answer #030
bts profile pic
bts

Live demo

.header-align-right{
  display: flex;
  padding: 21px 0;
  justify-content: flex-end;
}
12 users liked answer #1dislike answer #112
umutesen profile pic
umutesen

please copy paste this code in your css

:host ::ng-deep .mat-sort-header-container { 
    display: flex;  
    justify-content: center; 
}

th.mat-header-cell, td.mat-cell { 
    text-align: center; 
}
5 users liked answer #2dislike answer #25
Ruben Aaron Hurtado Cruz profile pic
Ruben Aaron Hurtado Cruz

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).