Different Interpretation of TH Box Model Between B

2019-07-02 01:17发布

问题:

I'm noticing discrepancies between browsers in how the width of a TH tag is interpreted, specifically whether or not padding is included in the width calculation.

I am building a reusable library for quickly generating and styling tables (for tabular data, of course). This means that I have full control over the code I generate, but that I need to actually solve the problem versus finding a hack for a particular instance.

Simplest Description of the Problem

A TH in IE9 and FF is sized based on its padding + width (as expected). Chrome and Safari include the padding in the width, leading to undesirable results.

For example, if the cell is set to 16px wide + 4px of padding, IE9 correctly displays the cell as 20px wide. Chrome displays it as 16px wide.

Here is a JS Fiddle showing the differences: http://jsfiddle.net/CZnau/

You can see how the last cell is sized differently between browsers.

Notes

  • I am aware of box-sizing and even though the default is to not include the padding in width calculation of a cell, setting box-sizing: content-box explicitly does not fix the problem.

  • The fiddle shows a fixed layout table. I wish to use table-layout: fixed to handle display correctly in other scenarios. Specifically, my actual implementation uses text-overflow, wrapping management, and variable width layouts. In my testing using a fixed layout is the only reliable way to make all my requirements play together nicely. Plus, fixed layout tables potentially render more quickly.

  • I have tried setting the width explicitly on each TD, but this does not fix the issue (perhaps it conflicts with the fixed layout table?)

In case you want more details around why I need a fixed layout table, try this fiddle with and without table-layout: fixed and note the differences. With a fixed layout, the table is correctly sized to 100% and truncates text elegantly, even with a variable width cell.

http://jsfiddle.net/6GPmY/

回答1:

Firefox doesn't support box-sizing: content-box; yet, not even in their Aurora Version.

Until then you can use -moz-box-sizing:

th, td {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 8px;
}

jsFiddle Demo