Explain Codes LogoExplain Codes Logo

Applying an ellipsis to multiline text

html
responsive-design
css
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 16, 2025
TLDR

Get a multiline ellipsis using CSS. How? Simple! Conjure display: -webkit-box;, -webkit-line-clamp: 3;, -webkit-box-orient: vertical;. Here's how to do it:

.ellipsis-multiline { // Panic! At the Overflow overflow: hidden; // Working 9 to 5, what a way to make an ellipsis display: -webkit-box; // Yo Stack Overflow, I'm reorienting here! -webkit-box-orient: vertical; // Clamp my style! *Said no one ever* -webkit-line-clamp: 3; // Limit to 3 lines text-overflow: ellipsis; }
<div class="ellipsis-multiline"> // This will be the lorem of all ipsums! Multiline text that will truncate with an ellipsis after the third line. </div>

This CSS snippet truncates text after 3-lines, and -webkit-line-clamp is totally customizable.

It's not you, it's your width

To make your ellipsis fit like a glove, consider setting a max-width on the containing element:

.ellipsis-multiline { // Width you were here max-width: 250px; /* Adjusts width to text */ }

Also, ensure your visual aspect ratio is on point. Make it responsive for all screen sizes:

.ellipsis-multiline { // Width or without you width: 100%; /* Full container width */ // Maximum width-age people should attempt max-width: 600px; /* Ensure your text doesn't run off-screen */ }

Height control

When the height plays a crucial role, use max-height and line-height to control the visible lines:

.ellipsis-multiline { // Not too high, not too low max-height: 4.5em; /* For 3 lines, assuming line-height of 1.5em */ // Keeping the line-height in 'check' line-height: 1.5; }

Leaving it to JavaScript

When times get tough, max-width or -webkit-line-clamp not doing it for you? Resort to jQuery dotdotdot:

$(".ellipsis-multiline").dotdotdot({ // This height limit is 90px, trespassers will be truncated! height: 90, });

Customizing the ellipsis

Boost your ellipsis logic with :before and :after pseudo-elements:

.ellipsis-multiline::after { // Knock knock. Who's there? Ellipsis... content: '...'; /* Custom text for those who read between lines*/ // Right here, right now position: absolute; // I'm bottom text right: 0; bottom: 0; }

Blend this with position: relative in the container for a better fit.

Using CSS to spark joy

Enhance your ellipsis with these little touches:

  • text-align: justify; — To please the eye, and obsessive aligners.
  • display: block; or display: inline-block; — These define the ground rules when dealing with single line ellipsis.

Final tips and tricks

Test your solutions on practical platforms such as JSFiddle. Check out real-world examples (e.g., YouTube homepage). Practice makes perfect, my friends!