You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Material UI Accordion中居中Typography文本

解决Material UI Accordion内Typography文本居中问题

我在使用Material UI框架,想要让Accordion组件内Typography的文本居中显示。通过开发者工具将<AccordionSummary>的布局设置为grid时可以实现这个效果,但不知道怎么在代码里配置。我的代码如下:

<Accordion sx={{ background: "#141821" }}>
    <AccordionSummary>
        <Typography sx={{ color: `${colors.grey[100]}`, fontWeight: 'bold', textAlign: 'center' }}>Staff members on vacation</Typography>
    </AccordionSummary>
    <AccordionDetails>
        <Table>
            <TableHead>
                <TableRow>
                    <TableCell align="center"> Employee</TableCell>
                    <TableCell align="center"> Start Date</TableCell>
                    <TableCell align="center"> End Date</TableCell>
                </TableRow>
            </TableHead>
            <TableBody>
                <TableRow>
                    <TableCell align="center">
                        Michael 
                    </TableCell>
                    <TableCell align="center">
                        21-11-2023
                    </TableCell>
                    <TableCell align="center">
                        28-11-2023
                    </TableCell>
                </TableRow>
            </TableBody>
        </Table>
    </AccordionDetails>
</Accordion>  

解决方案

只需给<AccordionSummary>添加sx属性,将其布局设置为grid即可:

<Accordion sx={{ background: "#141821" }}>
    {/* 添加sx属性设置display为grid */}
    <AccordionSummary sx={{ display: 'grid' }}>
        <Typography sx={{ color: `${colors.grey[100]}`, fontWeight: 'bold', textAlign: 'center' }}>Staff members on vacation</Typography>
    </AccordionSummary>
    <AccordionDetails>
        <Table>
            <TableHead>
                <TableRow>
                    <TableCell align="center"> Employee</TableCell>
                    <TableCell align="center"> Start Date</TableCell>
                    <TableCell align="center"> End Date</TableCell>
                </TableRow>
            </TableHead>
            <TableBody>
                <TableRow>
                    <TableCell align="center">
                        Michael 
                    </TableCell>
                    <TableCell align="center">
                        21-11-2023
                    </TableCell>
                    <TableCell align="center">
                        28-11-2023
                    </TableCell>
                </TableRow>
            </TableBody>
        </Table>
    </AccordionDetails>
</Accordion>  

原理说明

默认情况下,AccordionSummary使用flex布局,内部的Typography元素不会自动占满整个容器宽度,因此textAlign: center仅在文本自身的宽度范围内生效,视觉上没有达到全局居中的效果。将AccordionSummary的布局改为grid后,内部的Typography会自动填充整个容器宽度,此时textAlign: center就能让文本在整个AccordionSummary范围内居中显示。


内容的提问来源于stack exchange,提问作者Felipe Useda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:00:34