【问题标题】:How to make ellipsis work in a flex container?如何使省略号在弹性容器中工作?
【发布时间】:2019-10-19 05:47:48
【问题描述】:

当我在 .container 上没有 display: flex 时,文本会在减小容器大小时正确截断。

但是绿色块和文本不再相邻,因为容器没有display: flex。当我将它添加到容器中时,绿色块和文本正确对齐,但文本不再被截断(省略号丢失)。

如何使用 flex 确保块和文本对齐,但文本在动态宽度容器中被省略号截断?

my example codepen

body {
  padding: 20px;
}

.container {
  display: flex;
}

.block {
  width: 25px;
  height: 25px;
  padding: 10px;
  background-color: yellowgreen;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px
}

.text {
  display: flex;
}

.truncate {
  flex: 1;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 20pt;
}
<div class="container">
  <div class="block">B</div>
  <div class="text">
    <div class="truncate">
      3. This is a long string that is OK to truncate please and thank you
    </div>
  </div>
</div>

【问题讨论】:

    标签: html css flexbox overflow ellipsis


    【解决方案1】:

    带有省略号的弹性项目必须能够缩小到内容的宽度以下。请在此处查看我的答案以获取完整的详细信息:Why don't flex items shrink past content size?

    revised codepen

    body {
      padding: 20px;
    }
    
    .container {
      display: flex;
      border: 1px dashed red; /* demo */
    }
    
    .block {
      flex: 0 0 25px;  /* flex-grow, flex-shrink, flex-basis */
                       /* set flex-shrink to 0 to prevent item from shrinking below 25px */
      padding: 10px;
      background-color: yellowgreen;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
    }
    
    .text {
      display: flex;
      min-width: 0; /* allow item to shrink below content size */
    }
    
    .truncate {
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 20pt;
      background-color: yellow; /* demo */
    }
    <div class="container">
      <div class="block">B</div>
      <div class="text">
        <div class="truncate">
          3. This is a long string that is OK to truncate please and thank you
        </div>  
      </div>
    </div>

    【讨论】:

    • 太棒了!感谢您的努力!
    • @TomAalbers 你只需要 min-width: 0; 在文本元素上
    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2017-05-08
    • 2016-09-12
    • 2012-06-01
    • 2022-07-19
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多