React MaterialUI中修改ListItem与ListItemIcon的min-width问题
调整Material UI ListItemIcon与文本的间距并修正图标居中问题
问题出在你直接修改了内部Icon的min-width,但ListItemIcon本身作为容器有默认的布局样式——包括固定的min-width和水平居中对齐,所以改Icon的样式不会影响容器宽度,自然调不了间距,还会让图标在容器内居中。
正确的做法是直接修改ListItemIcon的样式:
- 给
ListItemIcon设置min-width来控制和文本的间距 - 把
justifyContent设为flex-start,让图标靠左对齐(默认是center,导致图标居中)
修改后的完整代码:
return ( <ListItem component="li" sx={{ padding: 0, }} > <Link to={linkTo} style={{ textDecoration: "none", color: "inherit", width: "100%", padding: "16px", display: "flex", alignItems: "center", }} > {/* 调整ListItemIcon的样式 */} <ListItemIcon sx={{ minWidth: '32px', justifyContent: 'flex-start' }}> <Icon sx={{ color: isActive ? "black" : `${color}`, stroke: isActive ? "black" : `${color}`, strokeWidth: `${strokeWidth}`, }} /> </ListItemIcon> <ListItemText disableTypography primary={ <Typography variant="body2" style={{ color: isActive ? "black" : `${color}`, fontWeight: isActive ? "700" : fontWeight, fontSize: "1.3em", }} > {text} </Typography> } /> </Link> </ListItem>);
你可以根据需求调整min-width的数值(比如28px、36px),直到间距符合预期。
内容的提问来源于stack exchange,提问作者ganjelo
相关产品推荐
相关产品推荐

