DEV Community

Matt Miller
Matt Miller

Posted on

CSS Text Truncation: Techniques for Clean and Readable Displays

Introduction:
Effectively managing text display is crucial for maintaining a clean and readable user interface. In this post, we'll explore two CSS techniques for truncating text: one using the ch unit to limit characters, and the other employing line clamping to control the number of displayed lines. By implementing these techniques, you can ensure that your content remains concise and visually appealing.

CSS Truncate via ch Units

CSS Code:

.myClass {
  font-family: monospace;
  width: 2ch;
  overflow: hidden;
  white-space: nowrap;
}
Enter fullscreen mode Exit fullscreen mode

HTML Code:

<p class="myClass">
  My String
</p>
Enter fullscreen mode Exit fullscreen mode

Explanation:
The myClass CSS class is applied to a paragraph (<p>) element, limiting the width to 2ch (two characters). This creates a concise display by truncating the text and preventing line breaks.

CSS Truncate by Lines

Truncate 2 Lined

.truncate-2 {
  overflow: hidden;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  display: -webkit-box;
  font-size: 1.125rem;
}
Enter fullscreen mode Exit fullscreen mode

Truncate 3 Lined

.truncate-3 {
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  display: -webkit-box;
  font-size: 1.125rem;
}
Enter fullscreen mode Exit fullscreen mode

Truncate 4 Lined

.truncate-4 {
  overflow: hidden;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  display: -webkit-box;
  font-size: 1.125rem;
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
These CSS classes (truncate-2, truncate-3, truncate-4) employ the -webkit-line-clamp property to limit the displayed lines. By setting the desired number of lines and adjusting the font size, you can control the text presentation, ensuring a clean and organized appearance.

Benefits and Use Cases:

  • Responsive Design: Both techniques contribute to responsive and space-efficient text displays.

  • Consistency: Maintain a consistent and uniform design across different text elements.

  • Improved Readability: Prevent long strings from negatively impacting the layout, enhancing overall readability.

Conclusion:
By integrating these CSS techniques into your web development projects, you can effectively manage and truncate text, promoting a visually appealing and user-friendly experience. Experiment with different configurations to find the optimal balance for your specific design requirements.

Top comments (0)