如何限制网格中产品名称文本行数并添加省略号?
解决方案:固定产品名称为2行并添加省略号
text-ellipsis仅支持单行文本截断,要实现2行文本截断+省略号的效果,需要使用Tailwind的line-clamp-2工具类(该类已封装了overflow:hidden、display:-webkit-box、-webkit-line-clamp:2等必要样式)。
修改后的组件代码
只需修改产品名称的h2标签类名即可:
export default function Home() { return ( <div className="grid grid-cols-4 gap-10 py-4 px-6"> {products.map((product, idx) => ( <div key={idx} className="flex flex-col justify-between"> <div className="bg-white h-[200px] relative p-5 rounded-md flex items-center justify-center"> <Image src={product.image} alt={product.name} height={150} width={150} className="h-[150px] w-[150px] object-contain" /> </div> {/* 关键修改:替换text-ellipsis为line-clamp-2 */} <h2 className="mt-1 line-clamp-2">{product.name}</h2> <div className="flex justify-between mt-2"> <span>${product.price}</span> <button className="bg-[#5542F6] border-2 border-[#5542F6] text-white px-4 py-1 rounded-md flex items-center gap-1"> Add to cart </button> </div> </div> ))} </div> ); }
效果说明
修改后所有产品名称会被强制限制在2行内,超出的文本自动以省略号结尾,同时所有名称容器的高度统一,解决不同行之间名称区域高度不一致的问题。
内容的提问来源于stack exchange,提问作者Jevon Cochran
相关产品推荐
相关产品推荐

