Search code examples
htmlcsstailwind-css

Line-clamp works unexpectedly


I am trying to make line-clamp work. I use Tailwind CSS (unfortunately). As I did many times before I added utility class line-clamp-2 (I need to show only 2 lines of the text). As you can see ellipsis appeared but on the third line we see the other part of the text. Could someone help me, please? There is the mark up of that dropdown. Screenshot is attached either.

  <ul class="max-w-md rounded-xl bg-white py-2 text-sm shadow-2xl">
    <li
      class="my-0.5 px-3 py-2 font-medium line-clamp-2"
    >
      {{ currentUserAlias }}
    </li>
    <li v-for="(profileMenuItem, index) in items" :key="index" class="my-0.5">
      <Component
        :is="'a'"
        class="block whitespace-nowrap px-3 py-2 font-normal hover:bg-primary-100"
        :to="profileMenuItem.href"
        :href="getAbsoluteLink(profileMenuItem.href)"
      >
        {{ profileMenuItem.title }}
      </Component>
    </li>
  </ul>


Solution

  • Part of the text on the next line showed because of py-2 (padding will change element height). line-clamp-{n} utility adds dots at the end of n line but it does NOT magically removes text from the DOM (you may inspect it in a browser) - that is why it also adds overflow: hidden; property

    In order to fix it, add inner wrapper for your text and put line-clamp-2 on it

    <ul class="max-w-md rounded-xl bg-white py-2 text-sm shadow-2xl">
        <li
          class="my-0.5 px-3 py-2 font-medium"
        >
          <div class="line-clamp-2">
            {{ currentUserAlias }}
          </div>
        </li>
        
        // that part is irrelevant
      </ul>
    

    Now no matter what outer padding is you will have two clamped lines