在弹性行中使用`nowrap`时,请避免将最后一个元素推离屏幕

问题描述 投票:2回答:2

我需要在一行内渲染一个长文本。和一行中的图像(屏幕的紧密端)。

给定一个非常长的文本,我必须简单地截断它。现在该文本应该进入第二行,因为它太长了。

请看我的代码。如何避免将漂亮的表情符号推出屏幕?

请注意右侧的元素可能是动态的。所以给出一个固定的宽度是不够的。

div {
display:flex;
justify-content: space-between;
}

span {
white-space:nowrap;
overflow:hidden;
}
<div>
<span>hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
<span>🛑</span>
</div>
html css css3 flexbox nowrap
2个回答
2
投票

由于两个<span>元素都是overflow:hidden,第二个<span>也被截断。

一种解决方案是仅将文本元素设置为截断。 下面,我已经证明这也适用于多个图标。

body {
  margin: 0;
}

div {
  display: flex;
  justify-content: space-between;
}

.text {
  white-space: nowrap;
  overflow: hidden;
}
<div>
  <span class="text">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
  <span>🛑</span>
  <span>🛑</span>
  <span>🛑</span>
</div>

另一种解决方案是通过将flex-shrink设置为零来防止图标缩小。 下面,我使用flex shorthand来设置flex-growflex-shrinkflex-basis。 (也适用于不同宽度和多个图标的图标。)

body {
  margin: 0;
}

div {
  display: flex;
  justify-content: space-between;
}

span {
  white-space: nowrap;
  overflow: hidden;
}

.icon {
  flex: 0 0 auto;
}
<div>
  <span>hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
  <span class="icon">🛑</span>
  <span class="icon">🛑🛑</span>
</div>

2
投票

你基本上只需要记住弹性项目可以默认收缩(flex-shrink: 1)。

一旦你禁用flex-shrink,你应该全部设置。

div {
  display: flex;
  justify-content: space-between;
  align-items: baseline;    /* optional */
}

span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;  /* optional */
}

span:last-child {
  flex-shrink: 0;
}
<div>
  <span>hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
  <span>🛑</span>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.