Explain Codes LogoExplain Codes Logo

Wrap a text within only two lines inside div

html
responsive-design
css
performance
Alex KataevbyAlex Kataev·Sep 29, 2024
TLDR

To wrap text inside a div into two lines, use CSS property line-height to define single line height with max-height equal to double the line-height. Add overflow: hidden; to cut off extra text and text-overflow: ellipsis; to show a "..." as an indication of more content. For example:

.two-lines { display: block; /* blocks party like its 1999 */ line-height: 1.2em; max-height: 2.4em; /* twice the groove */ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; /* keep it together, man */ }
<div class="two-lines"> Lengthy text demonstrating that the text wraps in two lines. If the text is longer, it's truncated and ellipsis is shown. </div>

Note that the text does not break lines due to the white-space: nowrap; property. For multiline ellipses, we need additional CSS properties.

Understanding CSS in depth

Adaptation across various screens

In responsive design, the ellipsis should adapt to varying div widths. For this, use vendor-prefixed CSS properties to get a multi-line truncation that works regardless of how many characters or what width the container div is.

.multi-line-ellipsis { overflow: hidden; display: -webkit-box; /* every apple aficianado's best friend */ -webkit-line-clamp: 2; /* don't play more than 2 songs */ -webkit-box-orient: vertical; /* keep it upright, boss */ }

This text will adapt to two lines on wider screens, and three lines on narrower screens, with the ellipsis indicating more content.

Testing edge cases

Take into account dynamic changes due to user input like window resizing or font scaling - the implementation should be flexible.

Drawbacks of clamping

Though -webkit-line-clamp is supported in most browsers, older ones might not. Always check compatibility and have a fallback ready.

Alternative: JavaScript

When to consider it

Only when CSS can't handle your creative needs. Javascript is useful only for dynamic adjustments.

JavaScript approach

Use a library to measure and truncate as desired, for example, Shave.js or jQuery.dotdotdot.

Striking the right balance

Ensure Javascript usage doesn’t compromise performance or user experience.