Algorithm for calculating variable column widths for set table width

后端 未结 3 1632
渐次进展
渐次进展 2021-01-02 10:16

I need to figure out an algorithm that will calculate the optimized size of the column widths given the following:

  • the width of the table is fixed to the size
3条回答
  •  清酒与你
    2021-01-02 11:05

    The W3C publishes algorithms for stuff like this in it's CSS 3 Tables Algorithms.

    A simpler algorithm that I have used successfully and is quite trivial to implement can be found in the HTML4.1 specs:

    The minimum and maximum cell widths are then used to determine the corresponding minimum and maximum widths for the columns. These in turn, are used to find the minimum and maximum width for the table. Note that cells can contain nested tables, but this doesn't complicate the code significantly. The next step is to assign column widths according to the available space (i.e., the space between the current left and right margins).

    For cells that span multiple columns, a simple approach consists of apportioning the min/max widths evenly to each of the constituent columns. A slightly more complex approach is to use the min/max widths of unspanned cells to weight how spanned widths are apportioned. Experiments suggest that a blend of the two approaches gives good results for a wide range of tables.

    The table borders and intercell margins need to be included in assigning column widths. There are three cases:

    • The minimum table width is equal to or wider than the available space. In this case, assign the minimum widths and allow the user to scroll horizontally. For conversion to braille, it will be necessary to replace the cells by references to notes containing their full content. By convention these appear before the table.
    • The maximum table width fits within the available space. In this case, set the columns to their maximum widths.
    • The maximum width of the table is greater than the available space, but the minimum table width is smaller. In this case, find the difference between the available space and the minimum table width, lets call it W. Lets also call D the difference between maximum and minimum width of the table.
      For each column, let d be the difference between maximum and minimum width of that column. Now set the column's width to the minimum width plus d times W over D. This makes columns with large differences between minimum and maximum widths wider than columns with smaller differences.

提交回复
热议问题