Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Material Table columns dynamic width to content

After a lot of tinkering I finally have a decent setup for my material table. It's got pagination, it's got sort, it's got all the goodies I need. However, it looks off because several of my columns are single digit values, and they have the same width as columns I would prefer to be larger (like the description which is wrapped excessively).

Being inexperienced in scss (and css for that matter) I'm at a loss for how to fix this. I attempted tinkering with the flex property in just about every way I could figure out, and it doesn't appear to change a thing on the table.

This issue is further complicated in that I cannot easily use the 'hack' of the material table generating classes based on the column identifier, as the columns are generated dynamically. I could pass in width information as well, but that seems like an unmaintainable hack.

Is there a way to apply styling to the entire table and header that would get me the desired look?

like image 414
Marshall Tigerus Avatar asked Jul 24 '26 13:07

Marshall Tigerus


1 Answers

I used this successfully with Angular10.

First, wrap your table with a div, like this:

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

then add this 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;
}

This will size the cells according to the content, and make your table horizontally scrollable!

like image 95
BernieSF Avatar answered Jul 28 '26 15:07

BernieSF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!