如何用TailwindCSS实现容器缩小时<p>子元素不换行并隐藏溢出?
解决TailwindCSS中flex容器缩小时文本截断失效的问题
你遇到的问题核心是第一个<p>元素没有被分配可收缩的空间,导致它始终按内容宽度撑开,不会触发溢出隐藏。只需调整几个Tailwind类就能解决:
修改后的代码
<div className='flex flex-row ml-3 space-y-1 items-end border' id='container-fb'> <div className='flex flex-row items-center' id='inner-fb-one'> <p className='flex-1 whitespace-nowrap overflow-hidden text-ellipsis'>truncate this first child as the container shrinks</p> <p className='shrink-0'>keep this the same size</p> </div> <div className='flex flex-row items-center' id='inner-fb-two'> <p className='flex-1 whitespace-nowrap overflow-hidden text-ellipsis'>truncate this first child as the container shrinks</p> <p className='shrink-0'>keep this the same size</p> </div> </div>
关键类说明
flex-1:让第一个<p>占据父flex容器的剩余空间,容器缩小时会优先挤压这个元素的宽度whitespace-nowrap:强制文本不换行overflow-hidden:隐藏超出元素宽度的文本text-ellipsis:可选,用省略号代替溢出的文本(不需要的话可以去掉)
为什么原来的代码无效?
原来的第一个<p>没有flex-1,它会默认根据内容宽度撑开,父容器没有限制时,它不会被挤压,自然不会触发overflow-hidden的效果。加上flex-1后,它的宽度会被父容器约束,容器缩小到一定程度就会触发文本截断。
内容的提问来源于stack exchange,提问作者rolias4031
相关产品推荐
相关产品推荐

