Explain Codes LogoExplain Codes Logo

Crop text too long inside div

css
responsive-design
best-practices
css-tricks
Nikita BarsukovbyNikita Barsukov·Jan 28, 2025
TLDR

To trim overflowing text and replace it with an ellipsis within a div, you can employ CSS as follows:

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

Then, use the truncate class on your div:

<div class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed laoreet...</div>

Here, the CSS styles ensure that any excessive text beyond the box's boundary gets an elegant ellipsis (...), presenting your content in a neat and accessible format.

Understanding the components

Before expanding on the CSS code above, here are the key components it employs:

  1. overflow: hidden; - hides off-screen content, anything outside our 'TV screen'.
  2. text-overflow: ellipsis; - applies a 'Hollywood cutting room' effect to off-screen text.
  3. white-space: nowrap; - prevents the 'Marquee' effect, keeping all text on a single, unwrapping line.

Digging deeper

Handling variable content length

Our .truncate class aims to handle text of any length. It avoids the need for JavaScript measuring or hardcoded character counts, offering a flexible text cropping system.

Responsive design considerations

For responsive designs, consider using max-width in relative units like em or vw. This ensures scalability among different devices, acting like a 'one-size-fits-all' TV screen:

.truncate-responsive { max-width: 20em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

Fine-tuning display properties

Sophistication enters when you want to control the size of the div. display: inline-block or display: block; along with a defined width does the trick. Set a line-height equal to the div's height to ensure text stays on one line, just like on a theater stage:

.truncate-tuned { display: inline-block; width: 100%; line-height: 1.5em; /* equal to div's height */ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

Testing and content cut-off

To ensure effectiveness, always test on various devices and screen sizes. Beware, occasionally overflow: hidden; might cut short the last visible letter - not the whole drama, but a small 'Editing Room' hiccup.

Adaptive text truncation

For responsive designs, using relative units (em, vw, etc.) for max-width presents a flexible approach:

.frame-responsive { max-width: 50vw; /* Adjusts based on viewport width */ /* Everything else stays the same */ }

Special characters and different languages

Working with special characters or different languages? text-overflow: ellipsis; might throw a wobbly. As with any staging operation, it's essential to rehearse with your specific script.

Incompatible browsers

Remember, not all audiences (read: browsers) appreciate our play. It's always best to check browser support for the text-overflow property to ensure compatibility.