Search code examples
csstruncateellipsis

How can I truncate the text to better fit available space


here is some sample code http://jsfiddle.net/XpLSZ/2/

<div class="main">
    <div class="item ">
        <img class ="icon" src="https://www.google.com/s2/favicons?domain=http://planet.clojure.in"/>
        <span class="title" >This is a test Long title</span>
        <span class="count" >(22)</span>
    </div>
</div>

.main{
   border-style: solid;
    border-width: medium;
    width:200px;
}
.icon{
    width:12px;
    height:12px;
}
.truncate {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

What I want is to have a row with icon.title and count and have the title truncate instead of wrapping, is this possible with css ? (I do not want count to be truncated) Now I do some truncation in JS but the problem is that layout is different in some browsers and also it brakes on some zoom levels.


Solution

  • 1) Update your markup so that count element is before the title.

    2) float the count element right

    FIDDLE

    <div class="main">
        <div class="item truncate">
            <span class="count">(22)</span>
            <img class="icon" src="https://www.google.com/s2/favicons?domain=http://planet.clojure.in" /> 
            <span class="title ">This is a test Long title </span>
        </div>
    </div>
    

    CSS

    .count {
        float:right;
    }
    

    UPDATE:

    Well it seems that FF doesn't like floating the count element, instead we can absolutely position the count element to the right, and leave space for it in the parent.

    Like so:

    FIDDLE

    .item {
        padding-right:25px;
        -moz-box-sizing: border-box;
        box-sizing: border-box; 
        position:relative;
    }
    
    .count {
        position:absolute;
        right:0;
    }