An overview of the

It happened about half a month ago when a Table component was being developed. The body of the Table is rendered with a div as a cell, and the header part is rendered with a native Table tag. When the width of the result is adapted, the header and the body are always unable to be aligned in sync, and there is an error of several pixels. The browser does not support decimal rendering when rendering table elements.

The analysis reason

Write a demo

<div class="stage"> <table class="table"> <tr> <td>Content</td> </tr> </table> </div> <style> * { padding: 0; margin: 0; }. Stage {width: 100.5px; height: 100px; background-color: red; }.table {width: 100.5px; background-color: blue; } </style>

The Chrome browser looks like this:

Set 100px to 100.1px, 100.5px, or 100.9px, and the effect will be the same.

This is really unbearable, direct help network, found that the relevant information is very few, the official website does not have relevant explanation, found a lot of reasons, such as:

  1. Browser minimum rendering unit. This is obviously unconvincing, and while the browser confirms the existence of a minimum rendering unit, it doesn’t explain why div renders floating point numbers and table doesn’t.
  2. StackOverflow talks about this

I don’t fully understand what the root cause is. However, no matter what the reason, we must first come up with a set of solutions, the time limit must not be missed!

The solution

I pondered a compatible scheme, then also a brainwave, thought of a way of processing.

The idea is very simple, that is, the cell width is first rounded down and evenly distributed, so that the actual cumulative width must be a little smaller than the ideal, and then the difference is distributed according to the index, so that although some cells are 1px wide, it does not affect the visual effect.

When I came up with this solution, I realized that this solution was the same as what I had done before to ensure that the percentages of a set of data add up to 100%.

/** * @AdjustWidth (Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth, Boolean isAdjustWidth. cols) { const cellWidth = Math.floor(baseWidth / cols); // Calculate the base cellWidth const offset = baseWidth-cellWidth * cols; // error const results = new Array(cols).fill(cellWidth); // If there is redundancy, reassign for (let I = 0; i < offset; i++) { results[i] = cellWidth + 1; } return results; } adjustWidth(1000, 3); // [334, 333, 333]