首页 > 解决方案 > 对齐两个 div 以使第二个 div 获得所需的所有空间

问题描述

我有一个容器 div,其中有两个 div 在两端(左右)对齐。我正在使用 flex 进行对齐,如下所示。

.box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 232px;
  height: 40px;
  margin: 0 auto;
  background-color: lightblue;
}

.name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.number {
  font-size: 14px;
  text-align: right;
  background-color: lightblue;
}

当两个 div 没有足够的空间来适应给定的宽度时,我希望右边的 div 占据它需要的所有空间,而右边的 div 缩小(并添加省略号)。但是,在某些情况下,我仍然看到第二个 div 中的内容转到下一行。有没有办法避免这种情况?请注意,在 jsFiddle 的示例中,“NUMBER”是如何被推送到下一行的。

http://jsfiddle.net/kLn9bm7w/

标签: htmlcssflexbox

解决方案


还要添加white-space: nowrap到右侧的 div ( .number)。

.box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 232px;
  height: 40px;
  margin: 0 auto;
  background-color: lightblue;
}

.name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.number {
    white-space: nowrap; /* new */
    font-size: 14px;
    text-align: right;
    background-color: lightblue;
}
<div class="box">
  <div class="name"><a href="#" target="_blank">Somereallylongtextcodssdmeshere</a></div>
  <mark class="number">21.0K NUMBER</mark>
</div>


推荐阅读