Sacha Tomey

Sacha Tomey's Blog

Auto text overflow CSS styling

I found a great little trick today whilst trying to fit a large amount of textual data onto a single grid type row.  Rather than allow the text to wrap, potentially making rows different heights or making all rows large enough to fit the extremes I decided to fix the size and add an ellipse (...) to the end of the row if the text exceeds the limit.  I think this only works on IE.. !
Before I found this trick I cheated slightly and 'guestimated' how many characters would fit on the row and added the ellipse manually.  Not any more !  Check out the box below:
Some long text that exceed... 
Notice the ellipse is placed at the end of the text.
The magic is done by the, previously unknown to me, CSS style: text-overflow.  If you set this to ellipsis most of the work is done.  You need to set a few other attributes to get the desired effect; overflow, width and white-space.  Here is the HTML that generated the box above:
<span style="
                text-overflow: ellipsis;
                overflow:      hidden;
                white-space:   nowrap;
                width:         180px;
                border:        1px dashed gray;">
    Some long text that exceeds the fixed width of the span tag used in this example.
This trick can be applied to table cells providing the table-layout CSS style attribute is set to fixed.