如何在浮动div上实现“text-overflow: ellipsis”效果?

13

我有两个按钮,一个在屏幕左边,一个在屏幕右边,希望在屏幕缩小的时候它们能够很好地折叠。视觉上,我想要的效果是这样的:

________________________________________________________________
|                                                               |
|   |LongTextButtonName|                 |LongTextButtonName|   | When the screen
|_______________________________________________________________| is large

_______________________________________
|                                      |
|   |LongTextBu...|  |LongTextBu...|   | When the screen is small
|______________________________________|

很不幸,现在我得到了这个:

________________________________________
|                                       |
|   |LongTextButtonName|                |
|                |LongTextButtonName|   | 
|_______________________________________|

我希望使用纯CSS的解决方案。

这是我当前的HTML和CSS(这里有一个演示):

<div class="button-container">
  <div class="left-button"><a>LongTextButtonName</a></div>
  <div class="right-button"><a>LongTextButtonName</a></div>
</div>

.button-container {
  min-width:320px;
}
.button-container > div {
  border: 1px solid gray;
  background-color: orange;
  min-width: 160px;
  padding: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.left-button {
  float: left;
}
.right-button {
  float: right;
}
1个回答

12
下面的小提琴是基于以下原理工作的:
  • 容器需要宽度才能触发溢出和省略号。
  • 为了允许盒子不断地折叠,我使用了百分比宽度。
  • 为了考虑填充,我使用了CSS3的 box-sizing:border-box;
请注意,由于box-sizing:border-box;,这种解决方案将无法在旧版浏览器上运行。
.button-container {
  min-width:320px;
}
.button-container > div {
  border: 1px solid gray;
  background-color: orange;
  max-width: 50%;
  padding: 8px;
  white-space: nowrap;
  overflow: hidden;
  box-sizing:border-box;
  text-overflow: ellipsis;
}
.left-button {
  float: left;
}
.right-button {
  float: right;
}

http://jsfiddle.net/UfxgZ/1/


太棒了!按钮周围应该有一些边距,但我会尝试调整百分比来解决这个问题。box-sizing: border-box 是什么作用? - Nick G.
请查看更新后的答案 - 它考虑了填充,以便浏览器将容器的宽度设置为50%减去16像素的填充。 - PassKit
有没有办法让其中一个浮动的div根据其内容缩小并与之一起工作?(使用inline-block显示) - Sean Aitken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接