I want to show you a small trick to know the size of an element, before rendering that element on the screen.
This trick can be useful for various ...
For further actions, you may consider blocking this person and/or reporting abuse
Ok, so hear me out, I swear I'm not crazy!
If you know the font size of the text in those two lines, in pixels, this might work...
I assume you get a string like a short description to display there, but at the end of two lines you have to truncate it and display the read more button.
You can calculate the width of the containing element using getComputedStyles then read it as pixels.
Divide that by your font size and you would know the maximum amount of characters you can fit in one line in that container. Multiply it by two and you have your two lines length.
Calculate the width of read more and remove it from the two lines length.
Now all you have to do is truncate the string you are receiving for those two lines at that length.
If you position:relative the container of the two lines. You can position the read more wherever you want using absolute values.
I saw where you said what the easiest way to do this was and this popped up in my mind.
Just wanted to share before I forgot, still reading...
I've tried that sort of process before in an application. The one with trying to use line height and the length of the line.
The problem is that it only works properly with monospace fonts. And as I've learned, the users rather dislike reading monospace fonts.
Not line height. Just length. You never check line height at all.
Ok hear me out both of you. JavaScript will be executed async after the painting so unless you are using react, svelte, angular or similar it may cause flickering. That being said I used similar trick on the past but with other purposes rather than adding a read more button in which case you need to add visibility: hidden, then to avoid flickering just add a min-height to the parent container and then give priority to this script execution
Ok so hear me out all of you 😋.
May I humbly present a solution that is CSS based and only uses JS for the expand, button name change and adding the expanded class.
At less than 50 lines of CSS (and it could be much less) and 20 lines of JavaScript (including the JS to handle the input change updating the CSS variable!) I think it does the job quite nicely.
One downside is it doesn't know if all the lines are shown on screen by default and so can only be used where you know that there will be lines hidden by your height limitation.
Oeh I like this one, thanks. But yeah, not knowing if all is shown, is too bad.
Looks like there is a CSS solution after all.
It uses shape-outside and it has pretty good browser support
The only caveat is that you need to know the height of the element you want in the lower-right corner.
There is a great article about it on CSS-tricks