Search code examples
csshtmlcss-floatellipsis

CSS text ellipsis when using variable width divs


I'm wondering if there is any way do have text in a floating div gain ellipsis when the parent div and neighboring div don't allow enough room. For example:

<style>
.parent-div {
    width: 100%;
    border: 1px;
    padding: 4px;
}
.text-div {
    float: right;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;    
}
.icon-div {
    float: left;
}
</style>
<div class="parent-div">
  <div class="text-div">This is text I'd like to truncate when space doesn't permit</div>
  <div class="icon-div">X</div>
</div>

So far if I crunch the browser window, the parent div will collapse, then the white space in text-div will vanish, but when there is no more room, the ellipsis never kick in.

The only thing I can think to do is trigger an event when the window resizes and dynamically set a new fixed width on text-div, but this just feels inelegant, especially considering padding and other neighboring artifacts I'd have to subtract out to get a proper width.

Any thoughts on this one?

Here's a jsFiddle demo: http://jsfiddle.net/Blender/kXMz7/


Solution

  • You can use CSS3's flexible box layout to do this pretty intuitively:

    .parent-div {
        display: flex;
    }
    
    .text-div {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;    
    
        min-width: 0;
    }
    
    .icon-div {
        flex: 1;
    }​
    

    Demo: http://jsfiddle.net/Blender/kXMz7/1/