cssangulartypescriptsassangular-material

Angular Material Table - CSS to get headers to left align when text wraps


With the Angular Material Table component, by default, the column headers on a table will left align, which is great:

Left aligned headers

However, if there isn't enough room for the header then the text wraps, which is fine except that the text then center aligns...

Center align text

How do I make the text left align? I thought this would be straight forward, but I'm having issues. This also only appears to happen on headers with sorting, because if you remove the mat-sort-header directive from any of the header cells, things left align correctly.

I tried adding the following css class definition, but no luck:

.mat-sort-header-button {
    text-align: left;
}

Here is the demo I'm playing around with.


Solution

  • The reason why your styles is not working is that Angular uses Emulated encapsulation be default so your styles are component scoped. That means that you can only apply class to element which is placed in component template directly. You can't style nested components.

    enter image description here

    To style elements from nested components you have to use ::ng-deep selector:

    ::ng-deep .mat-sort-header-button {
      text-align: left;
    }
    

    Forked Stackblitz

    There are other ways to solve it: