如何设置HTML表格中textarea初始高度适配内容且与input标签基线一致
解决方案
核心思路是取消textarea的固定高度设置,统一input和textarea的基础盒样式,再根据内容自动适配初始高度。
方案1:纯CSS实现(适配Chrome 123+、Firefox 122+等现代浏览器)
利用CSS新增的field-sizing: content属性可以让表单控件自动根据内容调整尺寸,再配合最小高度保证和input对齐:
* { box-sizing: border-box; } table { background-color: gray; } /* 统一input和textarea的基础样式,保证高度计算基准一致 */ input, textarea { border: 1px solid #ccc; padding: 4px 6px; font-size: 1rem; line-height: 1.2; } textarea { /* 行高+上下内边距+上下边框,和同页面input高度对齐 */ min-height: calc(1.2rem + 8px + 2px); max-height: 3rem; field-sizing: content; /* 自动根据内容调整高度 */ resize: vertical; /* 可选,允许用户手动拉伸高度 */ }
方案2:全浏览器兼容方案(CSS+少量JS)
如果需要兼容旧版本浏览器,仅需在页面加载时执行一次高度计算即可,不需要监听输入事件,完全符合不需要实时调整的要求:
调整后CSS代码
* { box-sizing: border-box; } table { background-color: gray; } input, textarea { border: 1px solid #ccc; padding: 4px 6px; font-size: 1rem; line-height: 1.2; } textarea { min-height: calc(1.2rem + 8px + 2px); max-height: 3rem; resize: vertical; }
补充JS代码
// 页面DOM加载完成后执行 document.addEventListener('DOMContentLoaded', function() { // 遍历所有需要适配高度的textarea document.querySelectorAll('textarea.input-fit').forEach(textarea => { // 重置高度后设置为内容高度,避免内容溢出 textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; }) })
内容的提问来源于stack exchange,提问作者logicOnAbstractions
相关产品推荐
相关产品推荐

