【问题标题】:How to limit grid cell width and prevent its content from overflowing?如何限制网格单元格宽度并防止其内容溢出?
【发布时间】:2021-07-01 02:10:17
【问题描述】:

我正在使用的生成 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 以编程方式设置,我不知道那种颜色。 我也无法将长文本包装成span 或其他东西,因为正如我所说,这个结构是由第三方 JS 库动态创建的。

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

【问题讨论】:

标签: html css flexbox css-grid


【解决方案1】:

由于没有太多上下文,因此很难确定,但如果我正确理解您想要实现的目标,我会这样做:

.select-option-secondary-text {
position: absolute;
left: 200px; [or whatever the value should be]
}

另外,如果你删除了网格的东西,你可以将text-overflow: ellipsis 添加到你的.select-option-text div。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 2018-04-25
      • 2020-06-19
      • 2012-03-16
      • 2016-11-05
      • 2021-12-16
      • 2016-09-28
      • 2021-05-16
      相关资源
      最近更新 更多