能否在标签内使用Flexbox布局?

6

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

这个方法一直很好用,直到我需要把整个列放到table-cell中 - 这时浏览器(Chrome)就忽视了列宽,并使表格足够宽以适应所有文本。

以下是标签布局:

<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 中则无法正常工作。
示例: 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>

更新: 最终我使用了更多的弹性盒子而不是表格来“解决”这个问题,但我仍然想知道原始示例为什么无法正常工作。
1个回答

18

这是因为默认情况下,表格使用自动表格布局

CSS 2.1规范没有定义这种布局模式,但建议一种(非规范性)算法,该算法反映了多种流行的HTML用户代理的行为。

根据该算法,表格的width仅将被视为最小宽度,实际宽度足够以使内容不会溢出:

计算每个单元格的最小内容宽度(MCW):格式化内容可以跨越任意数量的行,但不能溢出单元格框。

由于您使用了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>

或者,您可以尝试固定表格布局,它在规范中有明确定义(因此更可靠),通常更快,并且也解决了这个问题。

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>


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