如何使省略号在弹性容器中工作?

Tom*_*ers 5 html css overflow ellipsis flexbox

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

在此输入图像描述

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

在此输入图像描述

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

我的示例代码笔

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Mic*_*l_B 4

带有省略号的弹性项目必须能够收缩到内容的宽度以下。有关完整详细信息,请参阅我的答案:Why don't flex items Shrink Past content Size?

修改后的代码笔

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 */
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • @TomAalbers 你所需要的只是文本元素上的“min-width: 0;” (2认同)