I have a dynamic text in a span. I would like to use line-clamp: 2
.
In that case there are max. 2 lines of text and the rest is truncated by …
.
That works with:
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
My problem: If the content is truncated, a tooltip should be displayed. How can I detect whether the text is clamped?
The height of the element is the same, innerHTML
is same... I have no further idea...
CSS line-clamp Property The line-clamp property truncates a text at a specified number of lines. It limits the text, after you tell it the desirable number of lines, adding an ellipsis after the last word or portion of a word that is demonstrated. It is a shorthand for:
So, what’s the catch? As of right now, it’s browser support. Line clamps are part of the CSS Overflow Module Level 3 which is currently in Editor’s Draft and totally unsupported at the moment. We can get some line clamping action with a -webkit- prefix (which, weirdly enough, works across all major browsers).
As of right now, it’s browser support. Line clamps are part of the CSS Overflow Module Level 3 which is currently in Editor’s Draft and totally unsupported at the moment. We can get some line clamping action with a -webkit- prefix (which, weirdly enough, works across all major browsers).
We can get some line clamping action with a -webkit- prefix (which, weirdly enough, works across all major browsers). In fact, that’s how the demo above was done. We could go down the JavaScript path if we’d like. Clamp.js will do the trick:
Detecting CSS line-clamp
by javascript can be made by comparing the scrollHeight
and the clientHeight
of the "clamped" element.
The "true" height of the element is clipped by the overflow: hidden
CSS property, but the DOM property scrollHeight will report the full height, while the clientHeight reports the rendered height.
The below example shows a clamped text.
Try hovering it to see if detection logged. (text is editable)
const isTextClamped = elm => elm.scrollHeight > elm.clientHeight
const onMouseEnter = elm => {
console.clear()
console.log( isTextClamped(elm) )
}
p {
width: 200px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
resize: both; /* allowing resize for this demo only */
}
<p contenteditable spellcheck="false" onmouseenter="onMouseEnter(this)">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</p>
👉 Here's a Codepen which illustrates this live
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With