Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

html - text-overflow: ellipsis not working in a nested flex container

I have a component which consists of text next to a button. The text must shrink and get cut off if not enough space is available. Like this:

.container .box {
  background-color: #efefef;
  padding: 5px;
  border: 1px solid #666666;
  flex: 0 0 auto;
}

.container .text {
  flex: 1 1 auto;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.container {
  display: flex;
}
<div class="container">
  <div class="text">This is a text that is supposed to get truncated properly when needed.</div>
  <div class="box">Hello</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution

Add min-width: 0 to the outer flex item (.content / demo)

or

Add overflow: hidden to the outer flex item (.content / demo)


Explanation

An initial setting of a flex container is min-width: auto on flex items.

This means that a flex item cannot be smaller than the size of its content.

In your original code, the text box (a flex item) gets smaller due to overflow: hidden.

Without that rule, you'll have the same behavior as the second example.

Demo: When overflow: hidden is removed, first example behaves like second example.

In the second version of your code, the primary flex items are .side and .content.

By default, .content cannot be shorter than its content (regardless of flex-shrink)... until you override min-width: auto with min-width: 0 or, like the first example, apply overflow: hidden.

From the spec:

4.5. Implied Minimum Size of Flex Items

To provide a more reasonable default minimum size for flex items, this specification introduces a new auto value as the initial value of the min-width and min-height properties defined in CSS 2.1... read more

For another example see: Why doesn't flex item shrink past content size?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...