Text Truncation Without the Drama
Dom Jay
February 23, 2023
import LineClampDemo1 from '../../components/demos/LineClampDemo1.astro';
import CardDemo from '../../components/CardDemo.astro';
Let's take a general card layout, we've all seen this before right? Standard image, heading and text content. I'm leaving out a link, because how that is placed is a whole other thing.
You've got the markup done to the design, but haven't accounted for the huge amount of text that the client will undoubtedly drop into only some of them.
Yuck. So we need to trim it down, make it look a bit more visually pleasing to the user right? We could just add a to the cards, with an on the tag....maybe? Chuck in a few media queries to adjust for smaller screen sizes?
Well that looks terrible, and also ignores any padding that might around the content (hint: there is). We need to be able to trim the text off nicely, which is where comes in. Hooray!
Using this property allows any text to be cut off, with the end of the visible text be replaced with an ellipses. There's a few ways of doing this already kind of, using JS (there's even a handy (?) npm script to help line-clamp ), Clamp.js or the property, as shown below.
To break this down quickly, there's three properties being used to get this solution - , and . puts all the text on one line, disregarding the boundaries of the box, puts the familiar '...' at the end of the text that is visible, and ...well...hides the overflow of the content. Due to this, it only works if you want one line of text, no more. Not ideal.
is now supported across all major browsers - Chrome, Firefox, Edge, and Safari. The dependency is still required, but that's not a reason to avoid it - the co-dependency is fully specified behaviour and isn't going anywhere.
Let's throw this onto the tag that's used here (could also be a modifier on the parent block class if you're familiar with BEM)
We've got our that we need, and to set how many lines we want to keep visible. We still need otherwise we'll get a mix of a clamped line with an ellipses and also overflowing content. We've been using the property throughout this post, but it's an odd one. Technically it's deprecated, but it's a required part of using and browsers will continue to honour it to make the entire thing work. As of writing this, there's an unprefixed version of in development that drops the entirely, but it's not Baseline yet. For now, this four-line block is the correct production pattern and safe to ship without a preprocessor or a polyfill.
Sweet ๐ค - that's one client bug ticket in Trello that can go straight to Done.
Discussion in the ATmosphere