Is it possible to get Flexbox to work inside label?

前端 未结 1 858
小蘑菇
小蘑菇 2021-01-02 23:27

I\'m using flexbox to display a text label along with a numeric value in a narrow column, so that the text is truncated with ellipsis if it doesn\'t fit.

It worked f

1条回答
  •  清歌不尽
    2021-01-02 23:42

    That's because, by default, tables use the automatic table layout:

    The CSS 2.1 spec doesn't define that layout mode, but suggests a (non-normative) algorithm, which reflects the behavior of several popular HTML user agents.

    According to that algorithm, the table's width will only be treated like a minimum width, and the real width will be enough so that the content does not overflow:

    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.

    Since you have white-space: nowrap, the MCW will be the width of the full text.

    To avoid that, you can set the initial width of your first span to 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;
    }
    Very long label text 12345
    Very long label text 12345

    Alternatively, you may want to try the fixed table mode, which is properly defined in the spec (and thus more reliable), is usually faster, and solves the problem too.

    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;
    }
    Very long label text 12345
    Very long label text 12345

    0 讨论(0)
提交回复
热议问题