Check out our Angular Book Series.

Use CSS To truncate a string with an ellipsis

My expertise in UI programming is creating reusable components, but less so on the design side of things. Every once in while I discover something interesting about CSS that I feel is worth sharing. Today I'll show you how to truncate a string with an ellipsis, magically.

First, let's create a few H1:

<h1>First Item</h1>
<h1>Second Item</h1>

The truncating will work on any HTML element, I just chose H1 for easy code. How add some CSS:

h1 {
width: 150px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

First add a specific width. Then hide the overflow with overflow and prevent word wraps with white-space. Finally, specify the text-overflow to value ellipsis. This will force the text to truncate if it gets too long:

Play with the code over here.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version