Wrap a text within only two lines inside div
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:
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.
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.
Was this article helpful?