如何调整Material-UI Table组件的字体大小?求推荐方案
Hey there! I see you're trying to tweak the font size of your Material-UI Table and hit a snag with your initial approach—let's get this sorted out together.
Why Your Initial Code Didn't Work
The problem with your current setup is that the fontSize you added to the table class doesn't override the default styles of the TableCell component. Material-UI's TableCell has its own explicit font-size styling (inherited from the theme's typography.body1), which takes precedence over styles applied directly to the parent table element.
Recommended Solutions
1. Global Theme Override (Best for App-Wide Changes)
If you want all tables in your project to use the larger font size, customize your Material-UI theme to override the TableCell default styles:
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; // Create a custom theme const customTheme = createMuiTheme({ overrides: { MuiTableCell: { root: { fontSize: '40pt', // Your desired font size }, }, }, }); // Wrap your app (or the component with the table) in ThemeProvider function App() { return ( <ThemeProvider theme={customTheme}> {/* Your Table component goes here */} </ThemeProvider> ); }
2. Component-Specific Styling (For Individual Tables)
If you only want to adjust the font size for a single table, use makeStyles to target the TableCell elements within your table:
import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableCell from '@material-ui/core/TableCell'; import TableRow from '@material-ui/core/TableRow'; const useStyles = makeStyles(() => ({ largeFontCell: { fontSize: '40pt', }, })); function CustomTable() { const classes = useStyles(); return ( <Table> {/* Example TableRow with custom-styled TableCell */} <TableRow> <TableCell className={classes.largeFontCell}>Column 1</TableCell> <TableCell className={classes.largeFontCell}>Column 2</TableCell> </TableRow> </Table> ); }
3. Target All Cells in a Table with Parent Selector
You can also apply the style to the Table component and target all child TableCell elements using a nested selector:
const useStyles = makeStyles(() => ({ tableWithLargeFont: { '& .MuiTableCell-root': { fontSize: '40pt', }, }, })); // Usage <Table className={classes.tableWithLargeFont}> {/* Your table content */} </Table>
Pro Tip
If you're still having trouble, use your browser's developer tools to inspect the TableCell element. This will show you which styles are being applied and help you identify if there's a higher-priority style overriding your customizations.
内容的提问来源于stack exchange,提问作者Pedro Almeida

