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

屏幕缩小时实现文本省略效果,避免组件被挤压的问题

解决小屏幕下文本省略(Ellipsis)不生效且挤压组件的问题

问题原因

当前代码里,文本所在的flex子容器默认min-width: auto,空间不足时不会收缩,导致挤压其他固定宽度组件;同时虽然给span设置了ellipsis样式,但父容器没有限制宽度,省略效果无法触发。

解决方案

  1. 给文本容器添加min-w-0,允许它在空间不足时收缩,避免挤压其他元素
  2. 使用Tailwind自带的truncate类替代内联样式,实现文本省略效果,更符合规范

修改后的代码

const MusicCard = ({
  music,
  className,
  checked,
  onClick,
  provider,
  canPlay
}) => {
  return (
    <div
      className={twMerge(
        `w-full p-4 ${checked ? 'bg-music-card' : 'bg-white'} rounded-md flex flex-row justify-between items-center cursor-pointer apple-shadow`,
        className
      )}
      onClick={onClick}
    >
      <div className="flex flex-1 flex-row items-center">
        {canPlay ? (
          <button
            className="p-0 w-8 h-8 min-w-[32px] mr-2 rounded-full text-white flex justify-center items-center mobile:mr-4"
          >
            <PlaySVG style={{ width: 25 }} />
          </button>
        ) : null}

        <img
          id="image"
          className="w-[50px] h-[45px] z-2 mobile:w-[70px] mobile:h-[65px]"
          src={music.artworkURL}
        />
      
        {/* 新增min-w-0,确保容器可收缩 */}
        <div className='flex-1 ml-2 min-w-0'>
          {/* 用truncate类替代内联样式 */}
          <span className='font-semibold truncate'>
            {music.title || 'This is a long text message'}
          </span>
        </div>

        <div
          className={`w-[30px] h-[30px] flex ${checked ? 'border-none' : 'border-terciary'} border-1 items-center justify-center rounded-full ml-[30px]`}
        >
          {checked ? (
            <CheckIcon color={'#422D8F'} />
          ) : (
            <AddIcon className={"#120a31"} />
          )}
        </div>
      </div>

    </div>
  )
}

export default memo(MusicCard)

说明

  • min-w-0:解除flex子元素默认的最小宽度限制,让文本容器能随屏幕宽度收缩
  • truncate:Tailwind内置类,等价于white-space: nowrap; overflow: hidden; text-overflow: ellipsis;,简化代码
  • 左侧播放按钮、图片,右侧选择按钮都设置了固定宽度/最小宽度,确保它们不会被压缩,文本容器自动占据剩余空间,空间不足时触发省略效果

内容的提问来源于stack exchange,提问作者Nilton Schumacher F

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:55:06