Search code examples
csstailwind-css

How to truncate text in TailwindCSS?


I am using truncate in TailwindCSS to make text ellipsis if text-overflow more than one line but it does not work.

My code not works below:

<div className="ml-1 inline-block">
   <span>Label: </span>
   <span className="font-semibold truncate">
     long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
   </span>
</div>

How can I fix It?


Solution

  • UPDATE - LINE-CLAMP

    tailwind now have line clamp plugin by default. so you can just use line-clamp-1

      <div className="ml-1 inline-block w-[200px]">
         <span>Label: </span>
         <span className="font-semibold line-clamp-1">
           long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
         </span>
      </div>
    

    OLD ANSWER

    First thing first your parent or the element must have a specific width otherwise how the element suppose to know when to stop and truncate? also in order to truncate to work your element's display must not be display inline since span is display inline by default you should change it to block

      <div className="ml-1 inline-block w-[200px]">
         <span>Label: </span>
         <span className="font-semibold line-clamp-1">
           long texttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
         </span>
      </div>