如何在两端对齐的段落文本中间添加间隔并维持连续对齐?
解决两端对齐段落中间加间隔且文本跨列延续的问题
核心思路
别拆分两个独立的div,而是按行拆分文本,每行分成左右两段,中间留固定间隔,同时保证每行左右都两端对齐。用JS计算每行能容纳的单词,避免拆分完整词组(比如"George Washington"不会被拆成两行),再配合CSS实现对齐效果。
实现步骤
1. HTML结构
先准备好原始文本和结果容器:
<div class="text-source"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived </div> <div class="result-wrapper"></div>
2. CSS样式
设置行布局和两端对齐,兼容单行对齐:
.text-row { display: flex; justify-content: space-between; margin: 0.2em 0; } .text-left, .text-right { text-align: justify; width: calc(50% - 20px); /* 减去间隔的一半宽度 */ } /* 强制单行两端对齐,兼容多数浏览器 */ .text-left::after, .text-right::after { content: ""; display: inline-block; width: 100%; }
3. JavaScript处理逻辑
计算每行单词,拆分左右段,避免词组拆分:
const source = document.querySelector('.text-source').textContent.trim(); const resultWrapper = document.querySelector('.result-wrapper'); const gapSize = 40; // 中间间隔的像素宽度 const containerWidth = resultWrapper.offsetWidth; const halfWidth = (containerWidth - gapSize) / 2; // 拆分文本为单词+标点的数组,保留完整词组 const wordList = source.match(/[\w’'-]+|[.,!?;]/g) || []; let currentWords = []; let currentWidth = 0; // 临时元素用来计算单个单词的宽度 const tempEl = document.createElement('span'); document.body.appendChild(tempEl); tempEl.style.visibility = 'hidden'; tempEl.style.whiteSpace = 'nowrap'; wordList.forEach(word => { tempEl.textContent = `${word} `; const wordWidth = tempEl.offsetWidth; // 判断当前行加这个单词会不会超半宽 if (currentWidth + wordWidth <= halfWidth) { currentWords.push(word); currentWidth += wordWidth; } else { // 当前行满了,渲染该行 renderTextRow(currentWords); // 重置当前行,放入当前单词 currentWords = [word]; tempEl.textContent = `${word} `; currentWidth = tempEl.offsetWidth; } }); // 处理最后剩下的单词 if (currentWords.length > 0) { renderTextRow(currentWords); } document.body.removeChild(tempEl); // 渲染单行的左右部分 function renderTextRow(words) { // 找合适的拆分点,避免在标点或词组中间拆分 let splitPos = Math.floor(words.length / 2); // 如果拆分点是标点,往前移 while (splitPos > 0 && /[.,!?;]/.test(words[splitPos])) { splitPos--; } const leftPart = words.slice(0, splitPos).join(' '); const rightPart = words.slice(splitPos).join(' '); const row = document.createElement('div'); row.className = 'text-row'; const leftDiv = document.createElement('div'); leftDiv.className = 'text-left'; leftDiv.textContent = leftPart; const rightDiv = document.createElement('div'); rightDiv.className = 'text-right'; rightDiv.textContent = rightPart; row.appendChild(leftDiv); row.appendChild(rightDiv); resultWrapper.appendChild(row); }
关键细节
- 不会拆分完整词组:JS里会检查拆分位置,避免把带空格的专有名词拆成两半,解决你说的"George"单独一行、"Washington"跑到下一行的问题。
- 单行两端对齐兼容:用伪元素
::after强制单行文本撑满宽度,不用依赖浏览器的text-align-last属性。 - 自适应宽度:根据容器和间隔宽度自动计算左右段的可用空间,适配不同屏幕。
内容的提问来源于stack exchange,提问作者tim
相关产品推荐
相关产品推荐

