angular material 2 table header center alignment

2020-02-26 14:20发布

If md-sort-header is added into md-header-cell in md-table, it is always left-alignment. How to center-align header cells, such "name"?

<md-header-cell *cdkHeaderCellDef md-sort-header style="text-align:center"> 
      Name 
</md-header-cell>

plnkr

5条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-26 14:48

If you don't want all header cells to align-center you can combine two classes:

.mat-header-cell.text-center { text-align: center; }

Then on the html:

<th mat-header-cell *matHeaderCellDef class="text-center">Actions</th>
查看更多
Anthone
3楼-- · 2020-02-26 15:00

I think the given solutions to the problem are too strict in their approach, i had a similar issue where i needed to change some css properties of mat-sort-header-container , but dynamically.

I did something like Vega's answer but minutely different on how styles are taken :

::ng-deep .mat-sort-header-container{
    justify-content: inherit;
    /* other inheritable properties */
}

which opens some properties for its parent to style mat-header-cell which is in your html code so whatever style you provide in mat-header-cell and in the ng-deep which is inheriting from its parent then only those styles and none other than that would go down that hierarchy .

查看更多
疯言疯语
4楼-- · 2020-02-26 15:03

The accepted answer is correct. However, ::ng-deep is depreciated and maybe dropped in future (official documentation).

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

The proper way is to use ViewEncapsulation. In your component.ts, add the following:

import { ViewEncapsulation } from '@angular/core';

@Component({
    ....
    encapsulation: ViewEncapsulation.None
})

and override the class in your component.css file:

.mat-sort-header-container {
  display:flex;
  justify-content:center;
}
查看更多
Rolldiameter
5楼-- · 2020-02-26 15:11
.mat-header-cell {    text-align: center;    }
查看更多
趁早两清
6楼-- · 2020-02-26 15:12

Update for Angular Material 5.x.x, no need for ng-deep:

  mat-header-cell {
   display:flex;
   justify-content:flex-end;
  }

DEMO


md-header-cell get 'translated' to a container with class="mat-sort-header-container". Using that, you set its style with ng-deep. Use flexbox to center its content. Put the following in the components stylesheet:

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

DEMO

查看更多
登录 后发表回答