Material UI ItemList中如何调整RemoveCircleIcon位置靠近文本并移至右上角
问题原因
Chrome开发者工具盒子模型中紫色区域代表元素的外边距(margin),你当前看到的紫色区域是MUI的ListItem组件默认给secondaryAction预留的右侧间距,这是导致图标远离文本的核心原因。
调整方案
你只需要修改两处样式即可实现需求:
- 给
ListItem组件添加相对定位作为父级上下文,同时取消默认预留的右侧间距:
给每个ListItem添加如下sx属性:
sx={{ paddingRight: 0, position: 'relative' }}
- 给
IconButton添加绝对定位,调整位置到列表项右上角:
将IconButton的sx属性修改为:
sx={{ position: 'absolute', top: 4, // 可根据实际展示效果微调数值 right: 4, // 可根据实际展示效果微调数值 zIndex: 1, width: '15px !important', height: '15px !important' }}
修改后完整代码示例
<List style={{ display: "flex", flexDirection: "row", padding: 0 }}> <ListItem className={classes.removePerson} sx={{ paddingRight: 0, position: 'relative' }} secondaryAction={ <IconButton sx={{ position: 'absolute', top: 4, right: 4, zIndex: "1", width: "15px !important", height: "15px !important" }} > <RemoveCircleIcon sx={{ fontSize: "20px" }} /> </IconButton> } > <ListItemAvatar> <Avatar src="stuff.img" /> </ListItemAvatar> <ListItemText className={classes.peopleListSpacing} primary="Steve First Steve First Steve First" /> </ListItem> <ListItem className={classes.removePerson} sx={{ paddingRight: 0, position: 'relative' }} secondaryAction={ <IconButton sx={{ position: 'absolute', top: 4, right: 4, zIndex: "1", width: "15px !important", height: "15px !important" }} > <RemoveCircleIcon sx={{ fontSize: "20px" }} /> </IconButton> } > <ListItemAvatar> <Avatar src="stuff.img" /> </ListItemAvatar> <ListItemText className={classes.peopleListSpacing} primary="Steve First" /> </ListItem> </List>
内容的提问来源于stack exchange,提问作者Shinne
相关产品推荐
相关产品推荐

