How to set max-width for a table column with Material UI v5

Viewed 333

I'm trying to set a max-width for the cells that are part of a column of a material table, like you can do with Fluent UI's tables.

The table needs to have width: 100% and the cells need to be able to be smaller than the max-width.

After setting max-width to both the cells and their children, the cells still stretch to a greater width than the limit that was set, although less than it would otherwise.

I did manage to set a fixed width, however, although border-box doesn't seem to work with it, for some reason.

Is there a way to set a max-width to a column without limiting the size of the table or setting a fixed width?

Demo

Relevant sections:

const width = 100;
const style = {
  maxWidth: width,
  borderStyle: "border-box"
};
// inside head row
<TableCell align="right" sx={style}>
  <div style={style}>Protein (g)</div>
</TableCell>
// inside table row loop
<TableCell align="right" sx={style}>
  <div style={style}>{row.protein}</div>
</TableCell>
1 Answers

I hope I correctly understood your question. By default, MUI TableCell displays all cell contents. You may avoid cell content from overflowing, you can change it to { width: 100, max-width: 100, overflow: "hidden," textOverflow: "ellipsis"}. For more information regarding, why max-width alone doesn't work on TableCell max-width on table cells #2802.

import { styled } from "@mui/material/styles";
import MuiTableCell from "@mui/material/TableCell";

// set the entire last column with Mui 5 Styled-Component
const TableCell = styled(MuiTableCell)`
  :last-of-type {
    width: 100;
    max-width: 100;
    overflow: hidden;
    text-overflow: ellipsis;
  }
`;

OR

// set each cell
const style = {
  width: 100,
  maxWidth: 100,
  overflow: "hidden",
  textOverflow: "ellipsis",
  borderStyle: "border-box"
};

Related