Search code examples
cssbackgrid

How is "width: 100%" computed when I add an element to a table cell dynamically?


Backgrid allows editing values in a table, and accomplishes this by putting an <input type="text"> inside the <td>. The input is set to max-width: 100% but it still pushes the size of the column out farther in some cases.

For an example, see the grid on their Examples section and click an item in the "Population" column. When it gets the editor class, its padding is set to 0, and both the <td> and <input> have box-sizing: border-box, but the width of the column still increases.

So does width: 100% not mean 100% of the width of the <td> as it is at the time? Or is it just not possible to make this work using CSS only? I could probably use a backbone event to get the size of the td and then set the input to the same size but that sounds a bit hacky.


Solution

  • The way the width of table columns is calculated is not trivial. They try to distribute the available space among the columns in a way that columns with more content gets a bigger share.

    If you go and say "the content should be as big as the column" you make that even more complex because you create a ciruclar dependency between content width and column width.

    So does width: 100% not mean 100% of the width of the <td> as it is at the time?

    No. When anything changes, everything is updated. CSS does not keep a history, so it does not know the width of an element at a particular time. So width: 100% means that after everything was updated, the input will have the same width as the <td>. But that may be different from what it was before the change.

    I do not have the perfect solution for your problem, but these are some ideas:

    • check the column width before replacing the content using JavaScript (as you already noted in your question)
    • Use fixed table layout. This way all columns have the same width and will not change based on their content.
    • set contenteditable on the <td> instead of using an input element. This should not impact the columns width — at least not as long as you do not actually edit the content.