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

如何使用Flexbox实现ul列表自动换行且不重叠?

解决配料列表换行重叠与空间利用问题

修改后的代码实现

JSX部分

return (
  <Card {...props} className={` ${classes.root} ${rootClassName}`} onClick={onClick}>
    {children}
    <div className={classes.box}>
      <ul className={classes.toppingsList}>
        {props.pizzas?.toppings?.map((topping) => (
          <li key={topping.id} className={classes.list}>{topping.name}</li>
        ))}
      </ul>
    </div>
  </Card>
);

CSS部分

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    textAlign: 'center',
    padding: theme.spacing(2, 2, 2),
    height: theme.typography.pxToRem(500),
    '&:hover': {
      cursor: 'pointer',
    },
  },
  box: {
    minHeight: '300px',
    width: '100%',
    padding: theme.spacing(1),
  },
  toppingsList: {
    listStyle: 'none',
    margin: 0,
    padding: 0,
    display: 'flex',
    flexWrap: 'wrap',
    gap: theme.spacing(1),
    justifyContent: 'center',
  },
  list: {
    flex: '0 0 auto',
    minWidth: '60px',
    padding: theme.spacing(0.5),
    border: `1px solid ${theme.palette.grey[300]}`,
    borderRadius: theme.shape.borderRadius,
  }
}));

关键修改说明

  • 让列表容器真正实现换行:将ul设置为flex容器并开启flexWrap: wrap,同时用gap属性给配料项添加间距,彻底避免重叠问题。
  • 最大化利用剩余空间:把box的固定高度改为minHeight,卡片总高度固定为500px,减去头部内容和内边距后,剩余空间会自动分配给配料列表,支持堆叠更多选项。
  • 优化配料项布局:调整list的flex属性为0 0 auto,让每个项根据内容自适应宽度,同时设置minWidth防止内容被过度挤压,可选添加边框提升视觉清晰度。

可选:固定高度+滚动

如果需要保持配料区域固定高度,同时支持查看更多配料,可将box的样式改为:

box: {
  height: '300px',
  width: '100%',
  padding: theme.spacing(1),
  overflowY: 'auto',
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:05:27