
通过 css grid 布局替代 flexbox,结合 css 计数器与同步 dom 更新,可实现行号与 textarea 内容行严格对齐、滚动同步,无需手动计算偏移量或监听 scroll 事件。
通过 css grid 布局替代 flexbox,结合 css 计数器与同步 dom 更新,可实现行号与 textarea 内容行严格对齐、滚动同步,无需手动计算偏移量或监听 scroll 事件。
在构建类编辑器 UI(如轻量级代码编辑器、配置文件编辑面板)时,常需在
根本解法是放弃手动定位,转而利用 CSS Grid 的天然行列对齐能力:
- 将 .editor 设为 display: inline-grid,并定义两列:固定宽度的行号列(如 3em)和自适应的文本区域列;
- 行号容器(.numbers)与
- 使用 CSS counter-increment + ::before 伪元素自动生成行号,完全脱离 JS 渲染逻辑;
- 移除所有 onscroll 监听与 top/height 动态样式操作,仅保留 onkeyup 触发的纯 DOM 更新(重绘 数量)。
以下是精简可靠的实现代码:
<div class="editor">
<div class="numbers"></div>
<textarea wrap="off" onkeyup="updateRowNumbering()"></textarea>
</div>
<script>
const ta = document.querySelector('textarea');
function updateRowNumbering() {
const num = ta.value.split('\n').length;
const numbers = ta.parentNode.querySelector('.numbers');
numbers.innerHTML = Array(num).fill('<span>').join('');
}
// 初始化示例内容
ta.value = `One
Two
Three
Four
Five
Six
Seven
Eight`;
updateRowNumbering();
</script>
body, textarea {
font-family: 'Consolas', 'Courier New', Courier, monospace;
}
.editor {
display: inline-grid;
grid-template-columns: 3em auto; /* 行号列宽固定,文本列自适应 */
gap: 10px;
line-height: 21px;
background: #282a3a;
border-radius: 2px;
overflow-y: auto;
max-height: 250px;
}
.editor > * {
padding-top: 10px;
padding-bottom: 10px;
}
.numbers {
text-align: right;
background: #333;
padding-right: 5px;
}
.numbers span {
counter-increment: linenumber;
}
.numbers span::before {
content: counter(linenumber);
display: block;
color: #888;
font-size: 0.95em;
}
textarea {
line-height: 21px;
border: 0;
background: transparent; /* 关键:让左侧背景透出 */
color: #fff;
min-width: 500px;
outline: none;
resize: none;
padding-right: 10px;
}
✅ 优势总结:
- 零偏移风险:Grid 自动对齐每行基线,无 JS 定位误差;
- 性能更优:仅更新 DOM 结构(innerHTML),不触发重排(reflow);
- 语义清晰:行号与内容逻辑分离,维护成本低;
- 响应式友好:grid-template-columns 可轻松适配不同屏幕宽度。
⚠️ 注意事项:
- 确保 textarea 与 .numbers 的 line-height、padding-top/bottom 完全一致,否则会出现单行错位;
- 避免在
- 如需支持 Tab 键缩进,建议添加 onkeydown="if(event.key==='Tab'){...}" 处理逻辑,但不影响行号对齐机制。
此方案已在 Chrome/Firefox/Safari 中验证兼容,是构建轻量级可滚动带行号编辑器的推荐实践。










