代码之家  ›  专栏  ›  技术社区  ›  LiranC

在弹性行中使用“nowrap”时,避免将最后一个元素从屏幕上推出

  •  2
  • LiranC  · 技术社区  · 8 年前

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

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

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

    请考虑右侧的元素可能是动态的。因此,给出一个固定的宽度是不够的。

    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>
    2 回复  |  直到 8 年前
        1
  •  2
  •   showdev    8 年前

    因为两者 <span> 元素为 overflow:hidden ,第二个 <跨度(>); 也会被截断。

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

    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-grow , 弹性收缩 和 flex-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
  •  2
  •   Michael Benjamin William Falcon    8 年前

    基本上,您只需要记住,flex项在默认情况下可以收缩( 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>
    推荐文章