如何实现div内文本仅在展示2行及以上时才对首行缩进?
实现多行文本才首行缩进的两种方案
方案1:JavaScript实现(全浏览器兼容,自适应高度场景推荐)
通过动态计算文本实际渲染行数控制缩进样式,不受容器高度规则限制,兼容性最好。
基础样式定义:
.text-container { width: 300px; /* 按实际需求设置宽度 */ line-height: 1.5; /* 必须显式声明行高,用于行数计算 */ } .indent-first-line { text-indent: 2em; /* 按需调整缩进值 */ }
HTML结构:
<div class="text-container">你的纯文本内容</div>
逻辑代码:
function adjustIndent(container) { // 先移除缩进类,避免样式干扰高度计算 container.classList.remove('indent-first-line'); const computedStyle = window.getComputedStyle(container); const lineHeight = parseFloat(computedStyle.lineHeight); const contentHeight = container.scrollHeight; // 计算行数,处理小数误差 const lineCount = Math.round(contentHeight / lineHeight); if (lineCount >= 2) { container.classList.add('indent-first-line'); } } // 初始化调用 const textEl = document.querySelector('.text-container'); adjustIndent(textEl); // 监听窗口尺寸变化,适配容器宽度改变的场景 window.addEventListener('resize', () => adjustIndent(textEl)); // 若文本内容会动态更新,更新完成后手动调用adjustIndent(textEl)即可
方案2:纯CSS实现(固定高度容器、现代浏览器场景适用)
依赖CSS容器查询特性实现,无需JS,适合容器高度固定、仅需要兼容高版本浏览器的项目。
.text-container { width: 300px; line-height: 24px; /* 显式设置行高,单位固定为px方便计算 */ container-type: size; /* 若有上下padding,需要同步计算到min-height阈值中 */ padding: 4px 0; } /* 2行文本总高度=行高*2 + 上下padding,本示例阈值为24*2 + 4*2 = 56px */ @container (min-height: 56px) { .text-container { text-indent: 2em; } }
注意:该方案兼容Chrome 117+、Firefox 122+、Safari 17.4+,容器高度由内容自适应的场景下会失效。
内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture
相关产品推荐
相关产品推荐

