是否有可能让 Flexbox 在标签内工作?

Is it possible to get Flexbox to work inside label?

我正在使用 flexbox 在一个窄列中显示一个文本标签和一个数值,这样如果文本不合适,就会被省略号截断。

它工作正常,直到我需要将整个列放在一个 table 单元格中 - 此时浏览器 (Chrome) 只是忽略了列宽并使 table 宽度足以容纳所有文本。

这是标签布局:

<div class="line">
    <span>Very long label text</span>
    <span>12345</span>
</div>
.line {
    display: flex;
    width: 100%;
}
.line span:first-child {
    white-space: nowrap;
    flex-grow: 1;
    overflow: hidden;
    text-overflow: ellipsis;
}
.line span:last-child {
    flex-shrink: 0;
    margin-left: 5px;
}

将其放置在具有固定宽度的常规 div 中会按预期工作。将它放在 table-cell 中不会:

Fiddle: http://jsfiddle.net/98o7m7am/

.wrapper {
  width: 150px;
}
.table {
  display: table;
}
.table > div {
  display: table-cell;
}
.line {
  display: flex;
  width: 100%;
}
.line span:first-child {
  white-space: nowrap;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}
.line span:last-child {
  flex-shrink: 0;
  margin-left: 5px;
}
<div class="wrapper">
  <div class="line">
    <span>Very long label text</span>
    <span>12345</span>
  </div>
</div>
<div class="table wrapper">
  <div>
    <div class="line">
      <span>Very long label text</span>
      <span>12345</span>
    </div>
  </div>
</div>

更新:我通过使用更多的 flexboxes 而不是 tables 结束了 'solving' 这个,但我仍然想知道为什么原来的例子不起作用。

这是因为,默认情况下,tables 使用 automatic table layout:

CSS 2.1 规范没有定义布局模式,但提出了一种(非规范的)算法,它反映了几种流行的 HTML 用户代理的行为。

根据那个算法,table的width只会被当作最小宽度处理,真正的宽度就足够了,内容不会溢出:

Calculate the minimum content width (MCW) of each cell: the formatted content may span any number of lines but may not overflow the cell box.

因为你有 white-space: nowrap,MCW 将是全文的宽度。

为避免这种情况,您可以将第一个跨度的初始宽度设置为 0:

.line span:first-child {
  width: 0;
}

.wrapper {
  width: 150px;
}
.table {
  display: table;
}
.table > div {
  display: table-cell;
}
.line {
  display: flex;
  width: 100%;
}
.line span:first-child {
  width: 0;
  white-space: nowrap;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}
.line span:last-child {
  flex-shrink: 0;
  margin-left: 5px;
}
<div class="wrapper">
  <div class="line">
    <span>Very long label text</span>
    <span>12345</span>
  </div>
</div>
<div class="table wrapper">
  <div>
    <div class="line">
      <span>Very long label text</span>
      <span>12345</span>
    </div>
  </div>
</div>

或者,您可能想尝试 fixed table mode,它在规范中正确定义(因此更可靠),通常更快,并且也能解决问题。

table-layout: fixed;

.wrapper {
  width: 150px;
}
.table {
  display: table;
  table-layout: fixed;
}
.table > div {
  display: table-cell;
}
.line {
  display: flex;
  width: 100%;
}
.line span:first-child {
  white-space: nowrap;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}
.line span:last-child {
  flex-shrink: 0;
  margin-left: 5px;
}
<div class="wrapper">
  <div class="line">
    <span>Very long label text</span>
    <span>12345</span>
  </div>
</div>
<div class="table wrapper">
  <div>
    <div class="line">
      <span>Very long label text</span>
      <span>12345</span>
    </div>
  </div>
</div>