如何用HTML和CSS实现仿多输入框外观的textarea?
实现每行形似独立输入框的textarea样式
完全可以通过HTML和CSS实现这个需求,核心是用CSS背景模拟每行的分隔效果,同时保留textarea的原生输入功能,不用修改textarea的本质结构。
实现代码
HTML结构
<div class="form-group"> <label>My Text Area</label> <textarea class="form-control custom-textarea" rows="3" style="resize:none;"> This is to be the first row of the text area and the text entered in here should continue to the second row, if I specified the number of rows, for example three rows, then the text area will look like three diffrent inputs </textarea> </div>
CSS样式
.custom-textarea { /* 保留外层边框,去掉默认内部样式 */ border: 1px solid #ced4da; /* 调整内边距,让文本和分隔线对齐 */ padding: 8px 12px; /* 设置行高,匹配每行高度 */ line-height: 2; /* 用渐变生成水平分隔线,数量比设置的rows少1 */ background-image: linear-gradient(to bottom, transparent 0%, transparent calc(50% - 1px), #ced4da calc(50%), #ced4da calc(50% + 1px), transparent calc(50% + 1px), transparent 100%); /* 背景大小:宽度铺满,高度等于行高 */ background-size: 100% 2em; /* 背景起始位置,避开顶部内边距 */ background-position: 0 8px; background-color: #fff; } /* 聚焦时的样式保持表单统一风格 */ .custom-textarea:focus { outline: none; border-color: #80bdff; box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25); }
关键说明
- 用
background-image的线性渐变生成每行的分隔线,颜色#ced4da可根据表单风格调整,和控件边框色保持一致即可。 background-size的高度与line-height匹配,确保分隔线刚好落在每行文本的中间位置。- 保留了原生textarea的自动换行、输入限制等功能,视觉上却呈现出多行独立输入框的效果,完全符合设定rows为输入上限的要求。
内容的提问来源于stack exchange,提问作者Lukho Mdingi
相关产品推荐
相关产品推荐

