Adam Wojnar
Adam Wojnar

Reputation: 545

How to set smallest width on table column in Material-UI?

I'm building a website in React, using Material-UI. I have a table and was wondering, if it's possible to set column width to fit the data + some additional padding on both ends?

This is my table:

  <Table className={classes.table} size="small">
    <TableHead>
      <TableRow>
        <TableCell width="???">CA</TableCell> <--- Width should be as much as "Fit to data" + margin of X pixels
        <TableCell width="140px">CB</TableCell>
        <TableCell width="240px">CC</TableCell>
        <TableCell width="200px">CD</TableCell>
        <TableCell>CE</TableCell>
      </TableRow>
    </TableHead>
    <TableBody>
      {data.map((row) => (
        <TableRow key={row.id}>
          <TableCell>{row.ca}</TableCell>
          <TableCell>{row.cb}</TableCell>
          <TableCell>{row.cc}</TableCell>
          <TableCell>{row.cd}</TableCell>
          <TableCell>{row.ce}</TableCell>
        </TableRow>
      ))}
    </TableBody>
  </Table>

I'd like column CA to be minimal, just so it fits the data with additional space on both sides, so that content doesn't touch column borders.

I've tried:

  1. not declaring width at all - didn't work
  2. width="auto" - didn't work

Upvotes: 4

Views: 7910

Answers (1)

itaydafna
itaydafna

Reputation: 2086

You can target this th with css and set it to width: 1px; white-space: nowrap;

I think this should work in your case:

.MuiTableCell-head:first-child {
   width: 1px;
   white-space: nowrap;
}

And here's how this can be achieved using react inline-styling:

// You can also add padding or any other style props to this style object 

<TableCell style={{width: '1px', whiteSpace: 'nowrap'}}>CA</TableCell>

Upvotes: 3

Related Questions