Published on

Responsive line-clamp with TailwindCSS

Tailwind CSS

Supported by more than 97% of web browsers, the line-clamp property allows developers to limit the number of lines of a paragraph without resorting to weird tricks like arbitrary truncation of text based on a defined number of words or characters.

Using the line-clamp property with TailwindCSS

Unsurprisingly, TailwindCSS handles this property via the line-clamp-x class which also adds some required styles like overflow: hidden or display: -webkit-box amongst others allowing a wider range of support from web browsers.

Responsive line-clamp with TailwindCSS

If you wanted to hide some text on mobile then display it with the line-clamp property enabled, one would probably try to do someting like this:

<!-- đŸš« Not working -->
<p class="line-clamp-3 hidden md:block">Lorem ipsum dolor sit amet [...].</p>

Bummer, it doesn't work. While the text is correctly hidden on mobile, the line-clamp property seems to have no noticeable effect on desktop.

Actually, this behavior makes sense when diving a little more into the inner workings of this TailwindCSS class. As I was saying earlier, the line-clamp requires the -webkit-box display mode to render correctly. This display mode is set with the line-clamp class, but is then overstepped by the responsive md:block class that sets the display mode back to block with higher CSS specificity.

Keeping all this in mind, the correct way to handle this specific case is to let line-clamp do its work of settings the display mode responsively without adding any superfluous display: block declaration like so:

<!-- ✅ Working -->
<p class="hidden md:line-clamp-3">Lorem ipsum dolor sit amet [...].</p>