Why does flex-box work with a div, but not a table?

后端 未结 3 543
后悔当初
后悔当初 2020-12-03 14:37

The following simple snippet results in a single web page that takes up the available screen space with a header at the top, a footer at the bottom, and the main content tak

3条回答
  •  爱一瞬间的悲伤
    2020-12-03 15:03

    I think the problem is that the table box is placed inside a table wrapper box:

    the table generates a principal block box called the table wrapper box that contains the table box itself and any caption boxes

    So the table box is no longer a child of the flex container, and thus is not a flex item. The flex item is the table wrapper box, but you set the flex property to the table element, and

    values of non-inheritable properties are used on the table box and not the table wrapper box

    So your flex is used on a box which is not a flex item and thus is ignored.

    It might have worked if that property was used on the table wrapper box, but it's not possible to select it. Even if you could, it wouldn't be clear whether it should be sized according to the tabular layout it generates instead of by the the Flexbox layout in which it participates.

    The solution is simple:

    1. Place the table in a wrapper, which will be the flex item
    2. Size that flex item as desired using flex layout
    3. Take the table out of flow and give it definite lengths relative to the flex item

    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    body {
      display: flex;
      flex-flow: column;
    }
    h1, small {
      flex: 0 1 auto;
    }
    div {
      position: relative;
      flex: 1 1 0; /* Chrome needs non-auto flex-basis */
      overflow: auto;
    }
    table {
      position: absolute;
      height: 100%;
      width: 100%;
      left: 0;
      top: 0;
      table-layout: fixed;
      border-collapse: collapse;
    }
    td {
      border: 1px dotted;
      text-align: center;
    }

    Some Header

    This is equidistributed.
    This is also equidistributed.
    Some Footer

    Just for fun, a hacky way to avoid adding the wrapper would be styling the table as a block and the automatically inserted tbody as the table.

    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    body {
      display: flex;
      flex-flow: column;
    }
    h1, small {
      flex: 0 1 auto;
    }
    table {
      display: block;
      position: relative;
      flex: 1 1 0;
    }
    tbody {
      display: table;
      position: absolute;
      height: 100%;
      width: 100%;
      left: 0;
      top: 0;
      table-layout: fixed;
      border-collapse: collapse;
      box-sizing: border-box;
    }
    td {
      border: 1px dotted;
      text-align: center;
    }

    Some Header

    This is equidistributed.
    This is also equidistributed.
    Some Footer

提交回复
热议问题