The New CSS Property I Wish Existed Years Ago
I used to fix this with a JavaScript resize listener. Now field-sizing: content do it in one line. Here’s another feature that we as web developers have been waiting for for years. It is CSS field-sizing . It landed in Chrome 123, Safari 26.2, and most recently in Firefox 152. Making it available in all major engines. Here’s how it works. By default, text areas have a fixed size, and if the…
CSS has introduced a new property called field-sizing that allows text areas to dynamically resize based on their content. This eliminates the need for JavaScript resize listeners to achieve the same effect. The property landed in Chrome 123, Safari 26.2, and Firefox 152, making it available across all major browsers. To use field-sizing, simply add the field-sizing: content; declaration to a text area.
This tells the browser to size the text area based on its content. By default, text areas have a fixed size, and if the content doesn't fit, a scroll bar appears. However, with field-sizing: content; the text area will resize itself to fit its content, both in width and height. This is particularly useful when the content exceeds a certain number of lines, as it will allow for vertical scrolling.
The property also works on text inputs, including number inputs and search inputs, and respects placeholders. For select elements, it sizes to the selected option when displayed as a list box. Developers previously had to use JavaScript to measure the scroll height of a text area and update its inline height, but with field-sizing, it can all be done in one line of CSS.
Developers would typically reset the text area's height to 'auto' to ensure it doesn't grow when new text is added but shrinks when text is deleted. Then, they would read the scroll height and assign it as the new inline height. This process would repeat every time the user typed or deleted a character, continuously updating the layout.
The new CSS baseline property of field-sizing allows developers to achieve the same functionality with just one line of code. Developers can further customize the size by adding minimum and maximum heights using the min-height and max-height properties. However, it's important to note that if the resize property is set to 'both' on a text area, field-sizing will not have any effect.
When more text is added, the scroll bars will reappear, and it won't dynamically adjust the height. To prevent this, developers can set resize: none on the text area. Overall, field-sizing is a game-changer for developers, allowing them to remove a common JavaScript dependency and streamline their codebases.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.