【问题标题】:Align right one mat-header-cell in a angular material table with sort headers将角材料表中的一个 mat-h​​eader-cell 与排序标题对齐
【发布时间】:2019-08-02 17:55:33
【问题描述】:

我正在尝试将表格中的一个标题对齐。我试过了:

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

在一个类中并将其添加到mat-header-cell。这使文本正确对齐,但也为元素添加了奇怪的间距,使其与其余标题不对齐。在没有display:flex 的情况下也尝试过,但没有任何效果。

<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>

如您所见,我将单元格的内容对齐,我也想对齐标题。

【问题讨论】:

  • 请使用代码 sn-p 发布您的 HTML 和 CSS 以及到目前为止您尝试过的内容。

标签: css angular angular-material


【解决方案1】:

在使用&lt;mat-header-cell&gt;&lt;mat-cell&gt; 时默认通过flexbox 完成单元格对齐,但在使用&lt;th mat-header-cell&gt;&lt;td mat-cell&gt;不是。使用表格元素时,使用text-align 完成对齐。如果你一直强制使用 flexbox,使用thtd 的表格单元格可能会失去与表格其余部分的垂直对齐。

我发现设置text-align: right 和设置justify-content: flex-end 的组合效果最好。这样,带有display:table-cell 的元素使用text-align,带有display:flex 的元素使用justify-content

你的例子:

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

要让箭头显示在标题之前,您应该使用arrowPosition 属性。

另外,我建议使用自动添加的列类(.mat-column- + 区分大小写的matColumnDef 值)而不是添加class="header-align-right"。这将对齐页眉、单元格和页脚。所以这是我的建议:

.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>

【讨论】:

  • 这是一个更好的方法。
  • 不幸的是,如果您需要对齐按钮内的文本,它不起作用。当按钮文字溢出成两行文字时,默认居中对齐,没有办法对齐,因为是通过材质库添加的,在html中没有引用。因此,这不适用于该用例。这仅在您的表格单元格文本没有溢出到多行时才有效。
【解决方案2】:

Live demo

.header-align-right{
  display: flex;
  padding: 21px 0;
  justify-content: flex-end;
}

【讨论】:

  • 我现在这样做了.text-right { display: flex; justify-content: flex-end; padding: 5ex 0 5ex 0; },但基本相同。感谢您的帮助。
  • 如果有两列要右对齐,则上述答案失败。你能告诉我如何解决这个问题吗?
  • 如果文本溢出到两行文本中,这将不起作用。文本默认居中是因为它在button元素内,而且这个解决方案不对齐button元素,只对齐th元素。
【解决方案3】:

请将此代码复制粘贴到您的 css 中

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

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

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 1970-01-01
    • 2021-05-07
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多