【发布时间】: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 库动态创建的。
我能做些什么来防止文本溢出到下一个单元格,甚至可以用省略号截断它?
【问题讨论】:
-
如果 background-color 不是一个选项,那么你也应该包装那个文本,这样你就可以通过 CSS 选择器访问它的框来重置溢出和省略号。 jsfiddle.net/96ybuxho
-
如果不将长文本包装在 HTML 元素中,则在 CSS 中是不可能的。 like this... 和 you can't insert HTML elements using CSS pseudo elements.