使 Material Table 列的内容动态宽度

Making Material Table columns dynamic width to content

经过大量修改,我终于为我的 material table 设置了一个不错的设置。它有分页,有排序,有我需要的所有好东西。但是,它看起来不对,因为我的几个列是单个数字值,并且它们的宽度与我希望更大的列的宽度相同(就像过度包裹的描述)。

我在 scss(以及 css 方面缺乏经验)我不知道如何解决这个问题。我尝试以几乎所有我能想到的方式修改 flex 属性,但它似乎并没有改变 table 上的任何东西。

这个问题更加复杂,因为我不能轻易使用 material table 的 'hack' 根据列标识符生成 类,因为列是动态生成。我也可以传递宽度信息,但这似乎是一个无法维护的 hack。

有没有一种方法可以将样式应用到整个 table 和页眉,从而获得我想要的外观?

假设您的意思是 angular material table,这个可能会有所帮助: md-table - How to update the column width

对列宽使用以下样式,header

         columns={[
              {
                title: 'Create Date',
                field: 'create_date',
                cellStyle: {
                 whiteSpace: 'nowrap'
                },
               ...
               ]}
            options={{
              headerStyle: {
                backgroundColor: '#DEF3FA',
                color: 'Black',
                 whiteSpace: 'nowrap'
              },

我在 Angular10 中成功使用了它。

首先,用 div 包裹你的 table,像这样:

<div class='table-responsive'>
   <mat-table>
      ....
   </mat-table>
</div>

然后添加这个 CSS

.table-responsive {
 display: block;
 width: 100%;
 overflow-x: auto;
}

.mat-table {
 width: 100%;
 max-width: 100%;
 margin-bottom: 1rem;
 display: table;
 border-collapse: collapse;
 margin: 0px;
}

.mat-row,
.mat-header-row {
 display: table-row;
}

.mat-cell,
.mat-header-cell {
 word-wrap: initial;
 display: table-cell;
 padding: 0px 5px;
 line-break: unset;
 width: auto;
 white-space: nowrap;
 overflow: hidden;
 vertical-align: middle;
}

这将根据内容调整单元格的大小,并使您的 table 可水平滚动!