How can I make table columns resize when input text grows?
Asked by
MellowPine47
I have a table that fills 100% of its container. The first two columns have a minimum width of 40px, while the last header cell is set to width: 100% so the first columns stay as narrow as their content allows. Each data cell contains a text input. When a user types text that is wider than anything previously entered in a column, can I make the browser recalculate the table layout and expand that column automatically? Ideally, I'd like a CSS-only solution.
Answers
Try applying `field-sizing: content` to the inputs. It allows the input width to follow its content, which can cause the table column to recalculate as the user types. Itโs a neat CSS-only solution, but browser support is still limited, so check compatibility for your target browsers.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowPine47: That works perfectly for my use caseโthanks!
CedarLane29: If you need broader browser support, a common fallback is a hidden element that mirrors the inputโs value. Use JavaScript to measure that element and update the input or column width as the text changes.