CSS text ellipsis when using variable width divs

ⅰ亾dé卋堺 提交于 2019-12-17 07:20:07

问题


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/


回答1:


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/




回答2:


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/



来源:https://stackoverflow.com/questions/12649904/css-text-ellipsis-when-using-variable-width-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!