How to create dynamic text truncation based on window size, similar to Gmail's inbox?

I’m trying to recreate a cool feature I noticed in Gmail’s inbox layout. They have this neat trick where the middle column (which shows the email subject and a bit of the body) automatically adjusts when you change the window size. It cuts off the text perfectly so the sender and date columns always stay visible.

Here’s what I mean:

  1. Left column: Sender name
  2. Middle column: “Subject - Email preview”
  3. Right column: Date sent

When you make the window smaller, the middle part shrinks but the other two stay put. It looks really slick and I want to do something similar for my project.

Does anyone know how to pull this off? I’m guessing it involves some combo of HTML, CSS, and maybe JavaScript, but I’m not sure where to start. Any tips or code examples would be super helpful!

<div class="email-row">
  <span class="sender">John Doe</span>
  <span class="content">Meeting recap - Thanks for attending...</span>
  <span class="date">May 15</span>
</div>

How would I make the ‘content’ part adjust dynamically?

hey alice, i used css flexbox and a bit js to get dynamic text truncation working. use text-overflow: ellipsis in css and adjust the content width in js. hope it helps!

I’ve implemented a similar feature in a recent project. The key is using CSS flexbox for layout and the text-overflow property for truncation. Here’s a basic approach:

Set your container to display: flex and give fixed widths to the sender and date columns.

For the content column, use flex-grow: 1 to make it expand and fill available space.

Apply white-space: nowrap and overflow: hidden to the content span.

Use text-overflow: ellipsis for the ellipsis effect.

You might need some JavaScript to fine-tune the truncation on window resize, but this CSS foundation should get you most of the way there. Let me know if you need more specific code examples.

I’ve actually tackled this issue before in a client project. The trick is combining CSS flexbox with some clever JavaScript. Here’s what worked for me:

Set up your layout with flexbox, giving fixed widths to the sender and date columns. For the content, use flex-grow: 1.

In your CSS, add:

.content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Then, use a ResizeObserver in JavaScript to dynamically adjust the content width on window resize. This way, you can precisely control how much text is shown based on available space.

Remember to test on different devices and screen sizes. It took some tweaking, but the end result was smooth and responsive. Good luck with your implementation!