Flex布局下文本溢出省略号失效问题探讨

294 阅读2分钟
<div class="containter">
  <div class="left">left</div>
  <div class="right">
    <div class="content">
      省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字
    </div>
  </div>
</div>
.containter {
    width: 500px;
    height: 40px;
    display: flex;
    align-items: center;
    border: 1px solid black;
}
.left {
    width: 100px;
    height: 20px;
    flex: none;
    background-color: blanchedalmond;
}
.right {
    flex: 1;
    background-color: aquamarine;
}
.content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
  }

image.png

两个思路: 一、 去除content层级

<div class="containter">
  <div class="left">left</div>
  <div class="right">
      省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字
  </div>
</div>
.containter {
    width: 500px;
    height: 40px;
    display: flex;
    align-items: center;
    border: 1px solid black;
}
.left {
    width: 100px;
    height: 20px;
    flex: none;
    background-color: blanchedalmond;
}
.right {
    flex: 1;
    background-color: aquamarine;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
}

image.png 二、给right一个min-width:0

<div class="containter">
  <div class="left">left</div>
  <div class="right">
    <div class="content">
      省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字省略文字
    </div>
  </div>
</div>
.containter {
    width: 500px;
    height: 40px;
    display: flex;
    align-items: center;
    border: 1px solid black;
}
.left {
    width: 100px;
    height: 20px;
    flex: none;
    background-color: blanchedalmond;
}
.right {
    flex: 1;
    min-width: 0;
    background-color: aquamarine;
}
.content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
  }

image.png

总之给你要出现省略号的div一个固定的宽度就可以了

在 flex 布局中,flex: 1 的含义是该子元素将会均匀地分配父容器的剩余空间。具体来说,flex: 1 由三个部分组成:

flex-grow: 1 flex-shrink: 1 flex-basis: 0% 这意味着:

flex-grow: 1:当父容器有足够的空间时,该子元素将增长以占据剩余空间。 flex-shrink: 1:当父容器空间不足时,该子元素将缩小以适应父容器。 flex-basis: 0%:该子元素的初始大小为零,但它会根据 flex-grow 和 flex-shrink 的值来增长或缩小。 为什么需要 min-width: 0? 当我们在 flex 子元素上设置 flex: 1 时,该子元素会尝试占据父容器的剩余空间。但是,如果子元素内部还有其他内容(如文本),并且这些内容有一定的宽度,那么子元素可能会有一个默认的最小宽度。

默认情况下,浏览器会根据子元素的内容来计算一个最小宽度。如果我们希望子元素能够收缩到零宽度,就需要显式地设置 min-width: 0。这样做的目的是确保子元素能够根据父容器的可用空间来调整其大小,而不会因为内部内容的宽度而导致子元素不能正确收缩。