Html 使用可变宽度 div 时的 CSS 文本省略号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12649904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS text ellipsis when using variable width divs
提问by Anthony
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:
我想知道当父 div 和相邻 div 不允许足够的空间时,是否有任何方法可以让浮动 div 中的文本获得省略号。例如:
<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.
到目前为止,如果我压缩浏览器窗口,父 div 将崩溃,然后 text-div 中的空白将消失,但是当没有更多空间时,省略号永远不会出现。
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.
我唯一能想到的就是在窗口调整大小并在 text-div 上动态设置新的固定宽度时触发一个事件,但这只是感觉不雅,尤其是考虑到我必须减去的填充和其他相邻工件才能得到适当的宽度。
Any thoughts on this one?
对这个有什么想法吗?
Here's a jsFiddle demo: http://jsfiddle.net/Blender/kXMz7/
这是一个 jsFiddle 演示:http: //jsfiddle.net/Blender/kXMz7/
回答by Blender
You can use CSS3's flexible box layout to do this pretty intuitively:
您可以使用 CSS3 的灵活框布局非常直观地做到这一点:
.parent-div {
display: flex;
}
.text-div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
}
.icon-div {
flex: 1;
}?
回答by Chase Sandmann
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.
我的公司还不支持 CSS3,但我能够用另一种解决方案解决这个问题。通过float
仅将属性应用于图标 div 并将其放在 HTML 中的首位,另一个 div 将保持垂直对齐,同时在空间不足时也会截断。
Examples: (icon on right) http://jsfiddle.net/qftWN/, (icon on left) http://jsfiddle.net/Nr2NN/
示例:(右侧图标)http://jsfiddle.net/qftWN/,(左侧图标)http://jsfiddle.net/Nr2NN/