Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize MUI Table styles - last-child

I am trying to adjust the padding of MUI Table. last-child gets padding 24px which I want to adjust. I have tried to override the theme and to use classes{{root: classes.xxx}} but am not able to change it.

Below is the code I used for overriding the theme (I have also tried to override MuiTableRow and MuiTableColumn):

const theme = createMuiTheme({
  overrides: {
    MuiTableCell: {
      root: {
        paddingTop: 4,
        paddingBottom: 4,
        '&  $lastChild': { paddingRight: '5px' },
      },
      paddingDefault: {
        padding: '40px 12px 40px 16px',
      },
    },
  },
});

This is the CSS that I am trying to change (the last cell of each row in the table):

.MuiTableCell-root-511:last-child {
    padding-right: 24px;
}

Hope someone can give a helping hand.

like image 373
Haze Avatar asked Sep 27 '18 08:09

Haze


3 Answers

Thats the right approach, you just have a few syntax errors in your JSS.

The last child selector should be:

'&:last-child': {}

Here a complete example

const theme = createMuiTheme({
  overrides: {
    MuiTableCell: {
      root: {
        paddingTop: 4,
        paddingBottom: 4,
        "&:last-child": {
          paddingRight: 5
        }
      }
    }
  }
});

Edit Material UI Override table padding on last child

like image 62
Luke Peavey Avatar answered Sep 18 '22 03:09

Luke Peavey


For those who don't want to override theme, you can achieve the same result by providing classes object prop as shown here.

const useStyles = makeStyles({
  cell: {
    '&:last-child': {
      paddingRight: 5,
    },
  },
});

Provide it to your TableCell as usual;

<TableCell className={classes.cell}>

This will override the &:last-child attribute of your cell. I've found this method to be a little more convenient when I'm not changing anything else in the theme.

like image 32
Kerem Avatar answered Sep 18 '22 03:09

Kerem


In MUI v5, you can use the sx prop and select the last TableCell like this:

<Table
  sx={{
    '& .MuiTableCell-root:last-child': {
      bgcolor: 'pink',
    },
  }}
>

Or if you want to use createTheme() to override globally:

const theme = createTheme({
  components: {
    MuiTableCell: {
      styleOverrides: {
        root: {
          '&:last-child': {
            backgroundColor: 'tomato',
          },
        },
      },
    },
  },
});

Live Demo

Codesandbox Demo

like image 37
NearHuscarl Avatar answered Sep 19 '22 03:09

NearHuscarl