首页 > 解决方案 > 如何限制网格单元格宽度并防止其内容溢出?

问题描述

我正在使用的生成 HTML 代码的框架输出以下内容:

body {
  width: 200px; /* ignore this, this is only for demonstration purpose */
}
<div class="select-option-text" style="white-space: nowrap; overflow: hidden;">
  Some very long text that should be truncated with an ellipsis if it's too long to fit
  <span class="select-option-secondary-text">Always show</span>
</div>

我想要实现的是始终.select-option-secondary-text在文本旁边可见。使用短文本,这可以正常工作,但如果文本像我的示例中那样长,它会将.select-option-secondary-text可见区域推开。

我无法使用 flexbox 解决这个问题,但我能够使用网格达到我的要求:

body {
  width: 200px; /* ignore this, this is only for demonstration purpose */
}

.select-option-text {
  display: grid;
  grid-auto-flow: column;
  grid-template-columns: minmax(0, 1fr) auto;
}
<div class="select-option-text" style="white-space: nowrap; overflow: hidden;">
  Some very long text that should be truncated with an ellipsis if it's too long to fit
  <span class="select-option-secondary-text">Always show</span>
</div>

但是,第一个“单元格”仍然溢出到第二个“单元格”中。使用背景颜色并不是一个真正的选择,因为.select-option-text它有自己的背景颜色,用 JS 以编程方式设置,我不知道那种颜色。我也不能将长文本包装成 aspan或其他东西,因为正如我所说,这个结构是由第三方 JS 库动态创建的。

我能做些什么来防止文本溢出到下一个单元格,甚至用省略号截断它?

标签: htmlcssflexboxcss-grid

解决方案


如果不将文本包装在自己的元素中,显然不可能使用 CSS。


推荐阅读