如何基于内容平衡容器内Grid列宽 限制总宽不溢出且内容最大化可见
纯CSS方案
该方案可覆盖绝大多数基础需求,无需JS介入,满足总宽度不溢出、优先短内容完整展示、超出自动省略的要求:
html, body { width: 300px; margin: 0; padding: 0; box-sizing: border-box; } html * { border: 1px solid black; box-sizing: border-box; } span { cursor: pointer; /* 溢出省略规则 */ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; /* 核心配置:允许grid项收缩到内容宽度以下,覆盖默认的min-width:auto规则 */ min-width: 0; } body { display: grid; grid-template-columns: auto auto; }
<span contenteditable></span> <span contenteditable></span>
方案局限:当两列内容总宽度超过容器宽度时,默认按平均比例收缩,无法严格匹配内容实际宽度的比例,如有等比例分配需求可使用下方JS方案。
轻量JS方案
该方案性能开销极低,可完全满足所有需求,包括按内容宽度比例分配列宽的可选目标:
html, body { width: 300px; margin: 0; padding: 0; box-sizing: border-box; } html * { border: 1px solid black; box-sizing: border-box; } span { cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } body { display: grid; }
<span contenteditable></span> <span contenteditable></span>
const gridContainer = document.body; const columns = Array.from(gridContainer.querySelectorAll('span[contenteditable]')); function updateColumnWidth() { // 临时放开宽度限制,测量内容实际宽度 gridContainer.style.gridTemplateColumns = 'max-content max-content'; const totalContentWidth = columns.reduce((sum, col) => sum + col.offsetWidth, 0); const containerWidth = gridContainer.offsetWidth; if (totalContentWidth <= containerWidth) { // 内容总宽度未超出容器,自动分配即可 gridContainer.style.gridTemplateColumns = 'auto auto'; return; } // 内容总宽度超出,按实际内容比例分配容器宽度 const widthPercent = columns.map(col => `${(col.offsetWidth / totalContentWidth) * 100}%`); gridContainer.style.gridTemplateColumns = widthPercent.join(' '); } // 监听内容编辑事件 columns.forEach(col => col.addEventListener('input', updateColumnWidth)); // 监听容器尺寸变化,适配响应式场景 new ResizeObserver(updateColumnWidth).observe(gridContainer); // 初始化列宽 updateColumnWidth();
内容的提问来源于stack exchange,提问作者user3310334
相关产品推荐
相关产品推荐

