代码之家  ›  专栏  ›  技术社区  ›  Andrew

角度材质表-文本换行时CSS使标题左对齐

  •  1
  • Andrew  · 技术社区  · 6 年前

    Angular Material Table 组件,默认情况下,表上的列标题将左对齐,这很好:

    Left aligned headers

    但是,如果页眉没有足够的空间,则文本将换行,这很好,只是文本将居中对齐。。。

    Center align text

    如何使文本左对齐?我以为这会很直接,但我有问题。这也只出现在带有排序的标题上,因为如果删除 mat-sort-header 指令的任何标题单元格,左对齐正确。

    我尝试添加以下css类定义,但没有成功:

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

    Here is the demo

    1 回复  |  直到 6 年前
        1
  •  5
  •   yurzui    6 年前

    样式不起作用的原因是Angular使用的模拟封装是默认的,因此样式是组件范围的。这意味着您只能将类应用于直接放置在组件模板中的元素。不能设置嵌套组件的样式。

    enter image description here

    要设置嵌套组件中元素的样式,必须使用::ng deep selector:

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

    Forked Stackblitz

    还有其他解决方法:

    • encapsulation: ViewEncapsulation.None

    • 使用全局样式

        2
  •  0
  •   Amith B    3 年前

    如果有人仍在寻找全局样式,请检查此项。

    StackBlitz link for sort header alignment

    用于排序标题或普通标题中的文本对齐

    th.text-align-left,th.text-align-left .mat-sort-header-button {
        text-align: left !important;
    }
    th.text-align-right,th.text-align-right .mat-sort-header-button {
        text-align: right !important;
    }
    th.text-align-center,th.text-align-center .mat-sort-header-button {
        text-align: center !important;
    }
    

    用于排序标头中的内容对齐

    th.align-center .mat-sort-header-container {
        justify-content: center;
    }
    th.align-right .mat-sort-header-container {
        justify-content: flex-end;
    }
    th.align-left .mat-sort-header-container {
        justify-content: flex-start;
    }
    

    您可以在中使用这些文本左对齐、左对齐等类