Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 955
Anthony Avatar asked Sep 29 '12 04:09

Anthony


People also ask

How do I make text ellipses in CSS?

To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: ''; . This keyword value will display an ellipsis ( '…' , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text.

How do you handle text-overflow in CSS?

A text-overflow property in CSS is used to specify that some text has overflown and hidden from view. The white-space property must be set to nowrap and the overflow property must be set to hidden. The overflowing content can be clipped, display an ellipsis ('…'), or display a custom string.

Can I use text-overflow ellipsis?

Definition and Usage. The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user. It can be clipped, display an ellipsis (...), or display a custom string.


2 Answers

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/

like image 58
Blender Avatar answered Sep 17 '22 14:09

Blender


My company does not support CSS3 yet, but I was able to solve the problem with another solution. By applying the float attribute only to the icon div and putting it first in the HTML, the other div will stay vertically aligned while also truncating when there is not enough room.

Examples: (icon on right) http://jsfiddle.net/qftWN/, (icon on left) http://jsfiddle.net/Nr2NN/

like image 42
Chase Sandmann Avatar answered Sep 17 '22 14:09

Chase Sandmann