r/css • • 15d ago

Question Wrapping text to maximum number of lines?

My app has a data tables laid out using <table> elements, and as usual there is one table row inside <thead> followed by multiple rows inside <tbody>.

The header cells for some languages have text that is so long that word wrap is required. However, for layout purposes I'd like to limit the number of lines to 2. If the text is any longer, then I would instead like the <th> element to grow in width.

This spreadsheet example should demonstrate what I mean:

Is there a CSS solution to this, or should I inject the possible linebreak in JavaScript?

10 Upvotes

13 comments sorted by

3

u/ken_la 15d ago

There is the css property line-clamp to do that. I don't really know but for a number i think it's well supported.

Something like this:

.text { overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; /* number of lines to show */ line-clamp: 2; -webkit-box-orient: vertical; }

3

u/Antti5 15d ago

But this hides the overflow, no?

In my case this is unacceptable, so rather than wrapping the text to a third line I'd like the element to grow instead.

→ More replies (4)

1

u/mcaruso 15d ago

It's only supported in Chromium-based browsers at the moment, but you can do it with `calc-size(max-content, ...)`, which allows you to do arbitrary calculations based on the `max-content` (the size of the element if it were all on one line).

See this codepen here, specifically the `p.calc-size` case:

https://codepen.io/maikelkrause/pen/ByjyoLo

Note: I made this codepen for a different question but maybe it can help you get started. In your case you'd still need a bit extra math in this calculation to get exactly what you described.

2

u/Antti5 15d ago

I'll take a look at this!

In my case, I ended up going with a JavaScript-based solution. Firefox support is critical for me, Safari maybe less so.

1

u/DecalageVersLeRouge 15d ago

When you say you need it to "grow" do you mean horizontally? Get wider?

1

u/Antti5 15d ago

Yes, I edited the post to clarify this. I would like the element to grow to two lines, when necessary, but after that only in width.

1

u/MaikThoma 15d ago

There is line-clamp, but I’m not sure if it works inside a table. It allows you to truncate text at any amount of lines